Busiest Stretches of a Garage from Gate Scanner Records
Greedy & IntervalsModel answerLast updated
Use unsorted gate scan records to find peak car occupancy and the maximal time windows at that peak, including when some exit scans are missing and stays are capped.
A parking garage records every gate scan as a triple:
[carId, time, eventType]
carIdis an integer that identifies a vehicle.timeis an integer timestamp.eventTypeis either'entry'or'exit'.
The records arrive in arbitrary order and may share timestamps. A car is considered inside the garage during the half-open range [entryTime, exitTime).
Assumptions for parts 1 and 2
- Every
'entry'has a matching'exit'for the samecarId, and the exit comes after the entry. - The same car never re-enters before it has left, so its stays do not overlap.
- At one timestamp, all exits are treated as happening before all entries.
Tasks
- Peak count. Return the largest number of cars that are inside the garage at the same moment.
- Peak windows. Return every maximal interval
[start, end)during which the number of cars equals that peak. Each interval must be as wide as possible: extending it on either side would lower the count. If the peak occurs in several disconnected windows, return all of them in time order. - Broken exit scanner. Now suppose some
'exit'records are lost, while every'entry'record is intact. Garage rules say no car stays longer than 2 hours, so for a car with a missing exit, its unknown departure timexsatisfiesentryTime < x <= entryTime + 2. Cars with a recorded exit use that time. Assuming the unknown departures are chosen to make the peak as large as possible, return the interval(s)[start, end)during which that largest possible occupancy can be reached.
Explain your algorithm for each part and give time and space complexity. Mention edge cases such as empty input, several events at the same timestamp, and touching intervals.
Hints
Hint 1
Turn each stay into two events, +1 at the entry and -1 at the exit, and sort them. Think about how the tie rule (exits first) maps onto the sort order of the deltas.
Hint 2
Occupancy only changes at event timestamps. Apply all events with the same timestamp together, then the count holds until the next distinct timestamp. Consecutive segments with the peak count that touch end-to-start must be merged.
Hint 3
For part 3, a later departure never lowers the count at any moment. So give every car with a missing exit the latest legal departure, but never later than that same car's next entry. Then rerun the part 2 sweep on the rebuilt stays.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
All three parts use a sweep line over +1/-1 events. Part 3 only adds a preprocessing step that fills in the missing exits.
Parts 1 and 2: sweep line
- Pair each car's entry with its exit to get half-open stays
[s, e). Alternatively, skip pairing and map each record directly: entry becomes(time, +1), exit becomes(time, -1). - Sort events by
(time, delta). Since-1 < +1, exits at a timestamp come before entries at that timestamp, which is exactly the tie rule. - Process events grouped by timestamp. After applying every event at time
t, the countcstays constant until the next distinct timestampt'. That gives a segment[t, t')with countc. - Part 1 is the largest
cover all segments. - Part 2 keeps the segments whose count equals that maximum, then merges touching ones (
prev.end == cur.start).
Merging is required. If one car leaves at t = 5 while another enters at t = 5, the count never dips, so [3,5) and [5,8) must be reported as [3,8) to be maximal.
Why it is correct
- Occupancy is a step function that changes only at event timestamps, so segments between consecutive distinct timestamps cover every value it takes.
- Inside a timestamp group, exits come first, so the count dips then rises. Only the count after the whole group describes the segment that follows.
- Half-open stays mean a car leaving at
tis not counted att. - After merging, the segment to the left of an interval has a lower count (or does not exist), and so does the one to the right (or the count falls to 0 at the end of the timeline). So each interval is maximal.
Part 3: missing exits
Step 1: rebuild stays per car
Group records by carId, sort each group by time (exits first on ties), and walk through while tracking an open entry:
- Exit with an open entry: close the stay at that time.
- Entry while another entry is still open: the earlier exit is missing. The car cannot re-enter before leaving, so close the old stay at
min(prevEntry + 2, thisEntry). - Entry still open at the end: close it at
entry + 2. - Exit with no open entry: impossible under the guarantees (all entries are logged). Ignore it or raise an error.
Step 2: sweep
Run the parts 1-2 sweep on the rebuilt stays.
Why the latest legal exit is optimal
- Take any valid assignment of unknown exits, with occupancy function
f. - Delaying a car's exit (while staying legal) only adds coverage, so it never lowers occupancy at any time.
- Hence the latest-exit assignment gives
f*withf*(t) >= f(t)for everytand every validf. - The best achievable peak is
M = max f*. - A time
tcan reachMunder some assignment exactly whenf*(t) = M. Iff*(t) < M, every validfis at mostf*(t)there. Iff*(t) = M, the assignmentf*itself does it.
So the maximal intervals of f* at level M are the answer, and one single assignment realizes all of them simultaneously.
The min(..., nextEntry) cap matters: without it, one car's rebuilt stays could overlap and be counted twice. It is still the latest valid exit, because an exit exactly at the next entry time is legal (exits precede entries on ties).
Units: "2 hours" equals 2 only if timestamps are in hours. Make the limit a parameter (for example 120 for minutes).
Complexity
Let n be the number of records.
| Part | Time | Space |
|---|---|---|
| 1 and 2 | O(n log n) for sorting, O(n) for sweep and merge | O(n) |
| 3 | O(n log n): grouping O(n), per-car sorts O(n log n) total, plus the sweep | O(n) |
If timestamps lie in a small bounded range T, a difference array replaces the sort and gives O(n + T) time.
Edge cases
- Empty input: peak is 0 and the interval list is empty. Do not report the whole timeline as a zero-occupancy window.
- Exit and entry at the same time: handled by the tie rule and the merge step.
- Many entries at one timestamp: processed as one group, so no artificial intermediate peaks appear.
- Several separate peak windows: all returned, in time order.
- Part 3, re-entry within the limit after a missing exit: the rebuilt exit is capped at the re-entry time.
- Zero-length stays: skip them, since
[t, t)covers nothing.
Code (Python)
from collections import defaultdict
def sweep(intervals):
"""intervals: half-open (start, end). Returns (peak, maximal peak intervals)."""
events = []
for s, e in intervals:
if s < e:
events.append((s, 1))
events.append((e, -1))
events.sort() # -1 sorts before +1: exits first
best = count = i = 0
n = len(events)
segments = []
while i < n:
t = events[i][0]
while i < n and events[i][0] == t:
count += events[i][1]
i += 1
best = max(best, count)
if i < n:
segments.append((t, events[i][0], count))
result = []
if best == 0:
return 0, result
for s, e, c in segments:
if c != best:
continue
if result and result[-1][1] == s:
result[-1][1] = e
else:
result.append([s, e])
return best, result
def rebuild(logs, max_stay=None):
by_car = defaultdict(list)
for car, t, typ in logs:
by_car[car].append((t, 1 if typ == 'entry' else 0))
stays = []
for evs in by_car.values():
evs.sort() # exits first on ties
open_t = None
for t, kind in evs:
if kind == 1:
if open_t is not None and max_stay is not None:
stays.append((open_t, min(open_t + max_stay, t)))
open_t = t
elif open_t is not None:
stays.append((open_t, t))
open_t = None
if open_t is not None and max_stay is not None:
stays.append((open_t, open_t + max_stay))
return stays
def peak_count(logs):
return sweep(rebuild(logs))[0]
def peak_windows(logs):
return sweep(rebuild(logs))[1]
def peak_windows_missing_exits(logs, max_stay=2):
return sweep(rebuild(logs, max_stay))[1]
Common mistakes
- Sorting by time only, so entries sneak ahead of exits at the same timestamp and inflate the peak.
- Recording a candidate peak in the middle of a timestamp group instead of after it.
- Forgetting to merge touching peak segments, which yields non-maximal intervals.
- In part 3, choosing the exit at
entry + 2without capping at the car's next entry, which double-counts the car. - Hard-coding
2when timestamps are not in hours.