KatInterview

Lantern Posts and Open Stretch Checks Along a Highway

Data Structure DesignAuto-graded · 17 test cases
MediumAuto-gradedData Structure Designfenwick-treebinary-searchcoordinate-compression

Last 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 mark x. No mark is recorded more than once.
  • ["ask", x, r]: a query asking whether a rest stop could be built that occupies every mark from x - r to x + 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 - r or x + r blocks the rest stop.
  • When r = 0, only the single mark x is checked.

Constraints

  • 1 <= len(events) <= 2 * 10^5
  • -10^9 <= x <= 10^9
  • 0 <= 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.