Lantern Posts and Open Stretch Checks Along a Highway
Data Structure DesignAuto-graded · 17 test casesLast updated
Process interleaved insert and query events on sparse integer coordinates, checking whether a symmetric window contains any previously inserted point, using binary search and a Fenwick tree.
A road crew is tracking broken lampposts along a very long highway. Positions are integer kilometer marks, and negative marks lie to the west of the depot. At the start, no lamppost is broken.
You are given a list of events, processed in order. Each event is a list in one of two forms:
["pin", x]: a broken lamppost is recorded at markx. No mark is recorded more than once.["ask", x, r]: a query asking whether a rest stop could be built that occupies every mark fromx - rtox + r, both ends included. The answer is"Y"if none of the broken lampposts recorded so far lies inside that range, and"N"otherwise. Queries never change the state.
Return a single string made of all query answers, concatenated in the order the queries appear. If there are no queries, return the empty string.
Implement:
def rest_stop_report(events: List[List[object]]) -> str:
Notes:
- Only lampposts recorded before a query count for that query; later ones are ignored.
- A lamppost located exactly at
x - rorx + rblocks the rest stop. - When
r = 0, only the single markxis checked.
Constraints
1 <= len(events) <= 2 * 10^5-10^9 <= x <= 10^90 <= r <= 10^9- Each
"pin"mark is unique across the event list. - Target time complexity: O(E log E), where E is the number of events.
Examples
Example 1
Input: rest_stop_report([['pin', 10], ['ask', 6, 3], ['ask', 6, 4], ['pin', 0], ['ask', 3, 3], ['ask', 5, 4]])
Output: 'YNNY'
Example 2
Input: rest_stop_report([['ask', -4, 0], ['pin', -4], ['ask', -4, 0], ['ask', -3, 0], ['ask', -2, 1]])
Output: 'YNYY'
Hints
Hint 1
A query answers Y exactly when the number of recorded points in [x - r, x + r] is zero, so you need point insertion plus range counting.
Hint 2
Coordinates are huge but there are at most 2*10^5 pins. Since the whole event list is given, gather all pin marks, sort them, and map each to a small index.
Hint 3
Use a Fenwick tree over the compressed indices. For a query, use bisect_left on x - r and bisect_right on x + r to find the index range, then compare two prefix sums. Alternatively, keep a sorted list of pins and check the first pin that is >= x - r.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A query answers "Y" exactly when the count of recorded pins inside [x - r, x + r] is zero. So the task reduces to two operations: add a point, and count points in a range. Coordinates are large and sparse, so we compress them.
- Read all
"pin"marks from the event list up front, deduplicate and sort them intopoints. Each mark gets a 1-based index in this sorted order. - Build a Fenwick tree (binary indexed tree) of that size, initially all zeros.
- Replay the events in order:
- For
["pin", x], add 1 at the index ofx. - For
["ask", x, r], findleft = bisect_left(points, x - r)(number of compressed points strictly below the window) andright = bisect_right(points, x + r)(number of compressed points at or below the window end). The count of pins currently recorded in the window isprefix(right) - prefix(left). If it is zero, append"Y", otherwise"N".
- For
- Join the answers.
Why it is correct
The Fenwick tree contains only pins processed so far, so later pins never affect earlier queries. The two bisect calls select exactly the compressed indices whose marks lie in [x - r, x + r], with both ends inclusive, so a pin at either boundary is counted. With no pins, the tree is empty and every query returns "Y". With r = 0 the window is a single mark and the same logic applies.
Complexity
- Sorting the pins: O(P log P).
- Each event costs O(log P) for the bisects and Fenwick operations.
- Total: O(E log E) time and O(P) space, where E is the number of events and P the number of pins.
Reference solution
from bisect import bisect_left, bisect_right
from typing import List
def rest_stop_report(events: List[List[object]]) -> str:
points = sorted({event[1] for event in events if event[0] == "pin"})
position_index = {value: i + 1 for i, value in enumerate(points)}
tree = [0] * (len(points) + 1)
def add(index):
while index < len(tree):
tree[index] += 1
index += index & -index
def prefix(count):
total = 0
while count:
total += tree[count]
count -= count & -count
return total
answers = []
for event in events:
if event[0] == "pin":
add(position_index[event[1]])
else:
x, r = event[1], event[2]
left = bisect_left(points, x - r)
right = bisect_right(points, x + r)
answers.append("Y" if prefix(right) == prefix(left) else "N")
return "".join(answers)