Seat Row Simulator: Leftmost Block Booking and Group Release
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate a row of seats where each booking takes the leftmost free block of a given length and a release frees all of a group's seats, efficiently on large inputs.
Seat Row Simulator
You manage one row of n seats, indexed 0 through n - 1. At the start every seat is empty. You receive a list of requests and must process them in order. Each request produces exactly one integer, and you return these integers as a list in request order.
There are two kinds of request:
- Reserve
[1, size, group]: find the leftmost run ofsizeadjacent empty seats. Among all windows ofsizeconsecutive empty seats, choose the one with the smallest starting index. Give allsizeseats togroupand output that starting index. If no such window exists, change nothing and output-1. - Release
[2, group]: empty every seat currently held bygroup, regardless of how many separate reservations produced them. Output the number of seats freed, or0if the group holds nothing.
Function
Implement simulate_seat_row(n, requests). It returns a list of integers, one per request, in the same order as requests.
Details
- The chosen window may start in the middle of a longer empty stretch. It only has to be
sizeconsecutive empty seats with the smallest possible first index. - A group may hold several disjoint blocks from reservations made at different times. A single release frees all of them.
- A group that already holds seats may reserve more. Its existing seats are unaffected.
- After a release, the same group identifier may reserve again as if it were new.
- A failed reservation (
-1) does not modify the row or any group's holdings.
Constraints
1 <= n <= 1000000 <= len(requests) <= 100000- In every reserve request,
1 <= size <= n. - Group identifiers are opaque, hashable tokens (for example, strings).
- Aim for roughly
O(log n)work per reserve. A release should costO(log n)per block the group holds. Rescanning the whole row on every request is too slow at the upper limits.
Examples
Example 1
Input: simulate_seat_row(10, [[1, 3, 'A'], [1, 2, 'B'], [1, 2, 'C'], [2, 'B'], [1, 3, 'D'], [1, 2, 'E'], [2, 'A'], [1, 4, 'F']])
Output: [0, 3, 5, 2, 7, 3, 3, -1]
Hints
Hint 1
The hard part is finding the leftmost window of `size` empty seats quickly. Think about a tree over the seats where each node summarizes its range, so you can rule out whole halves at once.
Hint 2
Per node, store the length of the empty run touching its left edge, the empty run touching its right edge, and the longest empty run inside. A run crossing the midpoint is the left child's right-edge run plus the right child's left-edge run.
Hint 3
To search, go left if the left child holds a long enough run. Otherwise check the run crossing the midpoint, and only then go right. Mark and unmark whole ranges with lazy assignment, and remember each group's (start, size) blocks so a release can undo them.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The main task is to find the leftmost window of size empty seats quickly while seats are repeatedly taken and freed. A segment tree over the seats, with lazy range assignment, does this.
Node data. Each node covers a range of seats and stores:
pre: length of the empty run that begins at the left end of the range.suf: length of the empty run that ends at the right end of the range.best: longest empty run anywhere in the range.
A parent combines its children A (left) and B (right) as follows:
pre = pre(A)ifAis not entirely empty, otherwiselen(A) + pre(B).suf = suf(B)ifBis not entirely empty, otherwiselen(B) + suf(A).best = max(best(A), best(B), suf(A) + pre(B)). The last term covers a run that crosses the midpoint.
Reserve. If the root's best is less than size, output -1. Otherwise descend from the root:
- If the left child has
best >= size, go left. Any window there starts earlier than one on the right or one crossing the midpoint. - Otherwise, if
suf(A) + pre(B) >= size, the answer ismid - suf(A) + 1. This is the earliest start of the crossing run. - Otherwise go right.
Then assign the range [start, start + size - 1] as occupied and record (start, size) under the group.
Release. Pop the group's recorded blocks. Assign each block's range as empty again and add up the sizes. If the group has no blocks, the answer is 0 and the tree is untouched.
Lazy assignment. Marking a range occupied or empty is a "set the whole range" operation. A node fully inside the range gets its three values set directly (all zero, or all equal to its length) and a pending tag. The tag is pushed to the children only when the search or a later update visits that subtree.
Why it is correct
The tree always reflects exactly which seats are empty. The descent order (left child, then crossing run, then right child) checks candidate windows in increasing order of start index, so the first one found has the smallest start. Every successful reservation records its block, so a release restores exactly the seats that group holds. Failed reservations change nothing.
Complexity
- Each search and each range assignment touches
O(log n)nodes. - A release costs
O(b log n)forbblocks, and each block is released at most once after being created. - Total time is
O((n + m) log n)roughly, more preciselyO(n + m log n)for building plusmrequests. - Space is
O(n)for the tree plus the stored blocks.
Reference solution
from typing import List
def simulate_seat_row(n: int, requests: List[List]) -> List[int]:
cap = 4 * n + 4
pre = [0] * cap # empty run touching the left edge of the node's range
suf = [0] * cap # empty run touching the right edge
best = [0] * cap # longest empty run inside the range
tag = [-1] * cap # -1 none pending, 0 set occupied, 1 set empty
def build(node, lo, hi):
length = hi - lo + 1
pre[node] = suf[node] = best[node] = length
if lo == hi:
return
mid = (lo + hi) // 2
build(node * 2, lo, mid)
build(node * 2 + 1, mid + 1, hi)
def apply(node, lo, hi, empty):
v = (hi - lo + 1) if empty else 0
pre[node] = suf[node] = best[node] = v
tag[node] = 1 if empty else 0
def push(node, lo, hi):
if tag[node] != -1 and lo < hi:
mid = (lo + hi) // 2
e = tag[node] == 1
apply(node * 2, lo, mid, e)
apply(node * 2 + 1, mid + 1, hi, e)
tag[node] = -1
def pull(node, lo, hi):
mid = (lo + hi) // 2
a, b = node * 2, node * 2 + 1
left_len = mid - lo + 1
right_len = hi - mid
pre[node] = pre[a] if pre[a] < left_len else left_len + pre[b]
suf[node] = suf[b] if suf[b] < right_len else right_len + suf[a]
best[node] = max(best[a], best[b], suf[a] + pre[b])
def assign(node, lo, hi, ql, qr, empty):
if ql <= lo and hi <= qr:
apply(node, lo, hi, empty)
return
push(node, lo, hi)
mid = (lo + hi) // 2
if ql <= mid:
assign(node * 2, lo, mid, ql, qr, empty)
if qr > mid:
assign(node * 2 + 1, mid + 1, hi, ql, qr, empty)
pull(node, lo, hi)
def find(node, lo, hi, need):
# Precondition: best[node] >= need.
if lo == hi:
return lo
push(node, lo, hi)
mid = (lo + hi) // 2
a, b = node * 2, node * 2 + 1
if best[a] >= need:
return find(a, lo, mid, need)
if suf[a] + pre[b] >= need:
return mid - suf[a] + 1
return find(b, mid + 1, hi, need)
build(1, 0, n - 1)
held = {}
out = []
for req in requests:
if req[0] == 1:
size, group = req[1], req[2]
if best[1] < size:
out.append(-1)
continue
start = find(1, 0, n - 1, size)
assign(1, 0, n - 1, start, start + size - 1, False)
held.setdefault(group, []).append((start, size))
out.append(start)
else:
group = req[1]
blocks = held.pop(group, [])
freed = 0
for start, size in blocks:
assign(1, 0, n - 1, start, start + size - 1, True)
freed += size
out.append(freed)
return out