Slot Availability Queries on a Sparse Number Line
Data Structure DesignModel answerLast updated
Handle an online stream of point-blocking and window-clearance queries on a huge integer line, and return a bit string with one result per query.
Blocked Cells and Clearance Queries
A warehouse aisle is modeled as an unbounded integer number line. Negative positions are allowed. At the start, every position is open.
You receive a list of operations and must process them in order:
["block", p]: positionpbecomes permanently blocked. It is guaranteed thatpis not blocked at the time this operation runs.["probe", c, r]: a pallet is considered whose footprint is centered at positioncand reachesr - 1positions to the left and to the right. Decide whether all positions fromc - (r - 1)throughc + (r - 1)(both ends included) are currently open. A probe is read-only and never blocks anything.
Return a single string that joins the answers of all probes in order: "1" if the window is fully open, "0" if at least one position in it is blocked.
Function signature
def probe_windows(operations: list[list]) -> str:
Rules
- A probe only reflects
blockoperations that appear earlier in the list. - The window has
2 * r - 1positions. Whenr = 1, only positioncis examined. - Each probe produces exactly one character. If the list has no probes, return
"".
Examples
operations = [["block", 2], ["probe", 0, 3], ["probe", 0, 2],
["block", -5], ["probe", -3, 3], ["probe", -3, 2]]
output = "0101"
The first probe covers -2..2 and includes the blocked 2, giving 0. The second covers -1..1, all open, giving 1. After blocking -5, the third probe covers -5..-1 and hits it, giving 0. The fourth covers -4..-2, open, giving 1.
operations = [["probe", 7, 1], ["block", 7], ["probe", 7, 1]]
output = "10"
Constraints
1 <= len(operations) <= 10^5-10^9 <= c, p <= 10^9,1 <= r <= 10^9- No position is blocked more than once.
- Window endpoints fit comfortably in a 64-bit integer.
What to provide
Explain your approach, give working code, and state the time and space complexity. Discuss how your solution behaves when there are up to 10^5 operations, not only on small inputs.
Hints
Hint 1
The line is far too large to store, but only the blocked positions matter. Ask what you need to know about them to decide whether any lies inside [lo, hi].
Hint 2
A window is fully open exactly when the smallest blocked position that is >= lo is either missing or greater than hi. Which search primitive finds that element?
Hint 3
A plain sorted Python list makes each insertion cost O(n) because of shifting. To get guaranteed O(log n) operations, think about reading all block positions ahead of time, compressing them to ranks, and counting blocked positions in a rank range with a Fenwick tree that only includes blocks that have already happened.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Only blocked positions matter, and there are at most 10^5 of them, while the coordinate range is about 2 * 10^9. So never build the line. A probe for window [lo, hi], with lo = c - (r - 1) and hi = c + (r - 1), answers "open" exactly when no blocked position lies in [lo, hi].
Equivalent test: find the smallest blocked position that is >= lo. If none exists, or it is > hi, the window is open. Otherwise it is blocked.
Approach 1: sorted list with binary search
Keep a sorted list blocked.
block p: insertpat its sorted position (bisect.insort).probe c r: computelo,hi, takei = bisect_left(blocked, lo), and answer0ifi < len(blocked)andblocked[i] <= hi, else1.
import bisect
def probe_windows(operations):
blocked, out = [], []
for op in operations:
if op[0] == "block":
bisect.insort(blocked, op[1])
else:
c, r = op[1], op[2]
lo, hi = c - (r - 1), c + (r - 1)
i = bisect.bisect_left(blocked, lo)
out.append("0" if i < len(blocked) and blocked[i] <= hi else "1")
return "".join(out)
Complexity: each probe is O(log n). Each insert is O(log n) to locate but O(n) to shift elements, so the worst case is O(n^2) element moves. In practice the shift is a fast memmove, and 10^5 inserts typically finish comfortably, but it is not a guaranteed bound. This is a reasonable first answer, and you should state the caveat out loud.
Approach 2: offline compression plus Fenwick tree (guaranteed O(log n))
Because the whole operation list is given up front, we can prepare a static index space even though the answers must respect time order.
- Collect every
blockposition and sort them into an arraycoords(all distinct, by the guarantee). Letk = len(coords). - Create a Fenwick tree of size
k, initially all zeros. - Process operations in order:
block p: find its rankj = bisect_left(coords, p)and add+1atj.probe c r: computelo,hi. Convert to a rank range:a = bisect_left(coords, lo)(first coordinate>= lo) andb = bisect_right(coords, hi)(one past the last coordinate<= hi). The number of currently blocked positions in the window isprefix(b) - prefix(a). Answer1if it is0, else0.
import bisect
def probe_windows(operations):
coords = sorted(op[1] for op in operations if op[0] == "block")
k = len(coords)
tree = [0] * (k + 1)
def add(i):
i += 1
while i <= k:
tree[i] += 1
i += i & -i
def prefix(i): # sum of first i ranks
s = 0
while i > 0:
s += tree[i]
i -= i & -i
return s
out = []
for op in operations:
if op[0] == "block":
add(bisect.bisect_left(coords, op[1]))
else:
c, r = op[1], op[2]
lo, hi = c - (r - 1), c + (r - 1)
a = bisect.bisect_left(coords, lo)
b = bisect.bisect_right(coords, hi)
out.append("1" if prefix(b) - prefix(a) == 0 else "0")
return "".join(out)
The key subtlety: the coordinate array contains positions that will be blocked later, but the Fenwick tree only holds a 1 for positions already blocked. A future block therefore never affects an earlier probe, which satisfies the "only earlier operations count" rule.
Complexity: sorting is O(n log n). Each operation is O(log n) for the binary searches and the Fenwick work. Space is O(n).
Alternatives
- A balanced BST or
sortedcontainers.SortedListgives the same O(log n) behavior without offline preprocessing, which matters if the stream is truly online and cannot be read ahead. - A segment tree over compressed coordinates works as well, but is heavier than needed since we only need counts.
Edge cases
r = 1collapses the window to[c, c].- No blocks yet:
bisect_leftreturns0on an empty list, so every probe is open. In the Fenwick version,k = 0and both prefixes are0. - A probe that precedes the block of the same position must return
1, while one after it returns0(second example gives"10"). - Negative coordinates and huge
rneed no special handling since only comparisons are used. Python integers avoid overflow. In fixed-width languages use 64-bit forc +/- (r - 1). - No probes: return
"".
Common mistakes
- Allocating an array or set over the coordinate range.
- Using the full window length as
rinstead ofr - 1on each side, which is an off-by-one. - Using
bisect_rightfor the lower bound orbisect_leftfor the upper bound in the Fenwick version, which excludes or includes boundary positions incorrectly. - Counting future blocks in the Fenwick tree by pre-filling it.
- Checking only the nearest blocked neighbor to
cinstead of the whole window. The first blocked position>= loapproach avoids this naturally. - Mutating state during a probe.
Summary
Start with a sorted list and bisect for clarity, then mention that list insertion is O(n) and upgrade to compression plus a Fenwick tree (or a sorted container) for a guaranteed O(n log n) total.