Concurrent Data Structures and Calendar Scheduling
Data Structure DesignModel answerLast updated
Build thread-safe request throttling, search from scratch, frequency-ranked retrieval, and multi-calendar availability finder.
You will implement four independent components that test your ability to design correct, efficient data structures and reason about concurrency, ranking, and calendar logic.
Part 1: Request Throttler
Create a throttling mechanism that accepts or rejects requests based on a sliding time window. Your implementation must:
- Track requests per client identifier
- Enforce a maximum number of requests within a rolling time window
- Support concurrent access from multiple threads safely
- Work without requiring the caller to supply the current timestamp
Interface:
throttler = RequestThrottle(max_requests=5, window_seconds=60.0)
allowed = throttler.check(client_id) # returns bool
Part 2: Search Implementation
Write a binary search function without using any standard library search methods. Your function should locate a target value in a sorted array and return its index, or -1 if not found. Handle edge cases including empty arrays, missing values, and duplicates correctly.
Part 3: Frequency-Based Ranking
Design a data structure that tracks item frequencies and efficiently retrieves the most frequent items. Requirements:
record(item)– increment the frequency of an itemtop(k)– return the k most frequent items
Optimize for the case where record is called much more often than top. Use a doubly-linked list internally to achieve constant-time frequency updates.
Part 4: Calendar Availability Finder
Build a system that finds open time slots across multiple people's calendars. Given:
- A set of calendars, each containing busy intervals as
(start, end)pairs - A desired meeting duration
- Working hours boundaries
Find all available slots where everyone is free for at least the requested duration.
Extension: How would you rank meeting rooms when multiple options exist? Consider factors like room capacity, previous usage frequency, and total time already booked.
Hints
Hint 1
For the throttler, think about what state must be updated atomically when checking a request.
Hint 2
Binary search maintains an invariant about where the answer can be. What should happen when the midpoint equals the target?
Hint 3
For top-k retrieval, organize items into buckets by frequency. How can you move an item between adjacent buckets in O(1)?
Hint 4
Calendar merging: sort all busy times, then identify gaps. A single pass can merge overlapping intervals while finding free windows.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Concurrent Data Structures and Scheduling
This problem evaluates your ability to design correct, thread-safe data structures and reason about intervals and ranking. The interviewer wants clean interfaces, careful handling of edge cases, and the ability to extend working implementations when requirements change.
Part 1: Request Throttler
Approach
Use a sliding window with request timestamps. For each client, maintain a queue of timestamps representing accepted requests. When a new request arrives:
- Remove all timestamps outside the current window
- Check if the remaining count is below the limit
- If yes, accept and record the timestamp
Thread safety: Wrap the read-check-update sequence in a lock. Without atomicity, two threads could both observe space available and both accept, violating the limit.
Time source: Accept an injectable clock function (defaulting to time.monotonic()) rather than requiring callers to pass timestamps. Monotonic time prevents issues when system clocks adjust.
Implementation
import threading
import time
from collections import deque, defaultdict
class RequestThrottle:
def __init__(self, max_requests, window_seconds, clock=None):
self.limit = max_requests
self.window = window_seconds
self.clock = clock or time.monotonic
self.requests = defaultdict(deque)
self.lock = threading.Lock()
def check(self, client_id):
now = self.clock()
with self.lock:
queue = self.requests[client_id]
cutoff = now - self.window
# Evict expired timestamps
while queue and queue[0] <= cutoff:
queue.popleft()
if len(queue) < self.limit:
queue.append(now)
return True
return False
Complexity: O(1) amortized per request, since each timestamp is enqueued once and dequeued once. Space is O(limit × clients).
Scaling: A single lock works for moderate load. For high concurrency, use lock striping (hash client IDs to one of N locks) or per-client locks with cleanup for idle clients.
Part 2: Binary Search
Approach
Implement find_position(arr, target) which returns the leftmost index where arr[i] >= target. This generalizes to exact search: if the returned index holds the target, it's found; otherwise it's the insertion point.
Invariant: The answer always lies in [left, right). The loop narrows this range:
- If
arr[mid] < target, the answer is strictly right of mid, soleft = mid + 1 - Otherwise, mid is a candidate answer, so
right = mid
When left == right, we've converged to the answer.
Implementation
def binary_search(arr, target):
left, right = 0, len(arr)
while left < right:
mid = left + (right - left) // 2
if arr[mid] < target:
left = mid + 1
else:
right = mid
# left is the first position >= target
if left < len(arr) and arr[left] == target:
return left
return -1
Why (right - left) // 2? In languages with fixed-width integers, (left + right) // 2 can overflow. This form avoids that.
Complexity: O(log n) time, O(1) space.
Edge cases: Empty array returns -1. Target smaller than all elements gives index 0; larger than all gives len(arr).
Part 3: Frequency-Based Ranking
Approach
Use a frequency bucket structure where items are organized into buckets by count:
- A doubly-linked list holds buckets in descending count order
- Each bucket stores the set of items with that exact frequency
- A hash map tracks which bucket each item belongs to
When an item's count increases, move it from its current bucket to the next higher bucket (creating it if needed). If a bucket becomes empty, unlink it from the list.
Retrieving top-k items walks the list from the head, collecting items until k are gathered.
Implementation
class FrequencyNode:
def __init__(self, count):
self.count = count
self.items = {}
self.prev = self.next = None
class FrequencyTracker:
def __init__(self):
self.head = FrequencyNode(float('inf'))
self.tail = FrequencyNode(0)
self.head.next = self.tail
self.tail.prev = self.head
self.item_location = {}
def _insert_after(self, node, new_node):
new_node.next = node.next
new_node.prev = node
node.next.prev = new_node
node.next = new_node
def _remove(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def record(self, item):
current = self.item_location.get(item, self.tail)
new_count = current.count + 1
# Find or create bucket for new_count
target = current.prev
if target.count != new_count:
target = FrequencyNode(new_count)
self._insert_after(current.prev, target)
target.items[item] = True
self.item_location[item] = target
# Remove from old bucket
if current is not self.tail:
del current.items[item]
if not current.items:
self._remove(current)
def top(self, k):
result = []
node = self.head.next
while node is not self.tail and len(result) < k:
for item in node.items:
if len(result) == k:
break
result.append(item)
node = node.next
return result
Complexity: record is O(1). top(k) is O(k) since every bucket has at least one item.
Why better than a heap? Heaps require O(log n) per update. This structure wins when updates vastly outnumber retrievals.
Part 4: Calendar Availability
Approach
- Collect and sort: Gather all busy intervals from every calendar, then sort by start time
- Merge and find gaps: Walk through sorted intervals with a cursor initialized to the work day start. For each interval
[s, e):- The gap
[cursor, s)is free if it's at leastdurationlong - Update
cursor = max(cursor, e)to merge overlapping intervals
- The gap
- Final gap: After processing all intervals, check
[cursor, day_end)
Implementation
def find_free_slots(calendars, duration, day_start, day_end):
busy = []
for cal in calendars:
busy.extend(cal)
busy.sort()
free_slots = []
cursor = day_start
for start, end in busy:
if cursor + duration <= start:
free_slots.append((cursor, start))
cursor = max(cursor, end)
if cursor + duration <= day_end:
free_slots.append((cursor, day_end))
return free_slots
Complexity: O(n log n) for sorting, O(n) for the sweep, where n is the total number of intervals.
Edge cases: Fully booked day returns empty list. Zero duration matches any gap.
Room Ranking Extension
When multiple rooms are available for a slot, rank them by:
- Utilization balance: Prefer rooms used less frequently to distribute wear
- Accumulated usage: Penalize rooms already booked for long total durations today
- Recency: Apply a small penalty for rooms just used (to allow cleaning)
A simple scoring function:
score = base_score - (0.3 * booking_count) - (0.5 * total_hours) - (0.2 * recency_penalty)
Pick the room with the highest score. This balances fairness with operational constraints.
Common Mistakes
- Throttler without atomicity: Checking count and adding a timestamp in separate operations creates race conditions.
- Binary search off-by-one: Setting
right = mid - 1whenarr[mid] >= targetskips the answer when mid is exactly the target. - Top-K using a min-heap of size k: Correct but O(log k) per update. The DLL structure is O(1).
- Calendar merge forgetting the final gap: After processing all intervals, the remaining time until
day_endmust be checked.