Restaurant Queue Tracker with Fast Rank Lookup
Data Structure DesignAuto-graded · 13 test casesLast updated
Replay a list of queue operations on a first-come waitlist, supporting add, remove-by-id, rank lookup and front peek, with rank queries faster than a linear scan.
Restaurant Queue Tracker
A restaurant keeps a queue of parties waiting for a table. Each party has a unique positive integer party_id and a head count. Parties are served in arrival order, but a party can also be removed from anywhere in the queue when it is seated.
You are given a batch of operations to replay in order against an initially empty queue. Return one result per operation.
Parameters
operations: a list of operation names.arguments: a list of the same length.arguments[i]holds the arguments foroperations[i].
Operations
| Operation | Arguments | Effect | Result |
|---|---|---|---|
add_party | [party_id, num_people] | Put the party at the back of the queue, unless that id is already waiting. | True if added, False if the id is already in the queue |
seat_party | [party_id] | Remove the party from the queue. | True if removed, False if the id is not in the queue |
get_position | [party_id] | Look up the party's current place in the queue, counting from 1 at the front. | The 1-based position, or -1 if the id is not in the queue |
get_next_party | [] | Peek at the party at the front without removing it. | The front party_id, or -1 if the queue is empty |
Rules
num_peopleis stored conceptually but never changes any result.- Once a party has been seated, its id is no longer in the queue, so it may be added again later and then joins at the back.
- A rejected
add_party(duplicate id) leaves the queue unchanged. - Removing a party shifts everyone behind it forward by one position.
Return the list of results in the same order as the operations.
Constraints
1 <= len(operations) == len(arguments) <= 10^5- Every
party_idis a positive integer. - Operation names are exactly one of
add_party,seat_party,get_position,get_next_party. - A position lookup should run faster than scanning the whole queue (aim for roughly O(log n) per operation).
Examples
Example 1
Input: replay_waitlist(['add_party', 'add_party', 'get_position', 'seat_party', 'get_position', 'get_next_party'], [[101, 4], [102, 2], [102], [101], [102], []])
Output: [True, True, 2, True, 1, 102]
Hints
Hint 1
A plain list or deque gives O(1) access to the front, but finding a party's rank or deleting from the middle costs O(n). A hash map of indices breaks because every removal shifts the later indices.
Hint 2
You need an ordered sequence that can answer 'how many elements come before this one?' and delete a specific element. Think of a balanced tree where each node stores its subtree size.
Hint 3
Alternative: assign each arrival an increasing sequence number and use a Fenwick tree over those numbers (1 for waiting, 0 for gone). Position is a prefix sum, and the front is the first set index. Keep a map from id to sequence number.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task needs an ordered sequence that supports three things quickly: append at the back, delete a specific element by id, and report how many elements precede a given one.
Simple structures each fail one requirement:
- A list or deque makes rank lookup and middle deletion O(n).
- A hash map from id to index makes rank O(1) but every removal shifts later indices, costing O(n).
Instead, use arrival order as a permanent coordinate:
- Every successful
add_partytakes the next sequence number (1, 2, 3, ...). Because new parties always go to the back, sequence numbers are in queue order. - A Fenwick (binary indexed) tree over the sequence numbers stores
1where the party is still waiting and0where it was seated or never existed. - Two dictionaries map
party_id -> slot(only for waiting parties) andslot -> party_id.
Operations:
add_party: if the id is in the map, returnFalse. Otherwise take a new slot, set it to 1 in the Fenwick tree, record the maps, returnTrue.seat_party: if the id is missing, returnFalse. Otherwise set its slot to 0, drop it from the maps, returnTrue. Re-adding the id later gives it a fresh, larger slot, so it joins at the back.get_position: the position is the number of waiting parties with slot less than or equal to its own, which is a Fenwick prefix sum.get_next_party: the front is the first slot with a 1. Find the smallest index with prefix sum at least 1 using Fenwick binary descent, then look up its id. If nobody is waiting, return-1.
Why it is correct
Slots are strictly increasing in arrival order and are never reused, so comparing slots equals comparing queue order. Removed parties contribute 0, so the prefix sum up to a party's slot counts exactly the waiting parties at or ahead of it, which is its 1-based position. The first slot with a 1 is the earliest still-waiting arrival, i.e. the front. The id maps contain exactly the waiting parties, so duplicate detection and the False / -1 answers are exact.
Complexity
- Time: O(log q) per operation, O(q log q) total for q operations.
- Space: O(q) for the tree and the maps.
Reference solution
from typing import List
def replay_waitlist(operations: List[str], arguments: List[List[int]]) -> List[object]:
n_ops = len(operations)
# Each add consumes one sequence slot (1-based). At most n_ops adds.
size = n_ops + 1
tree = [0] * (size + 1)
def update(i, delta):
while i <= size:
tree[i] += delta
i += i & (-i)
def prefix(i):
total = 0
while i > 0:
total += tree[i]
i -= i & (-i)
return total
# Largest power of two <= size, for k-th element search.
top_bit = 1
while top_bit * 2 <= size:
top_bit *= 2
def find_kth(k):
# Smallest index whose prefix sum >= k.
pos = 0
step = top_bit
while step:
nxt = pos + step
if nxt <= size and tree[nxt] < k:
pos = nxt
k -= tree[nxt]
step >>= 1
return pos + 1
slot_of = {} # party_id -> slot index while waiting
id_at = {} # slot index -> party_id
counter = 0
waiting = 0
results = []
for op, args in zip(operations, arguments):
if op == "add_party":
pid = args[0]
if pid in slot_of:
results.append(False)
else:
counter += 1
slot_of[pid] = counter
id_at[counter] = pid
update(counter, 1)
waiting += 1
results.append(True)
elif op == "seat_party":
pid = args[0]
slot = slot_of.pop(pid, None)
if slot is None:
results.append(False)
else:
del id_at[slot]
update(slot, -1)
waiting -= 1
results.append(True)
elif op == "get_position":
slot = slot_of.get(args[0])
if slot is None:
results.append(-1)
else:
results.append(prefix(slot))
elif op == "get_next_party":
if waiting == 0:
results.append(-1)
else:
results.append(id_at[find_kth(1)])
return results