KatInterview

Busiest Stretches of a Garage from Gate Scanner Records

Greedy & IntervalsModel answer
MediumModel answerGreedy & Intervalssweep-lineintervalsevent-processing

Last 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]

  • carId is an integer that identifies a vehicle.
  • time is an integer timestamp.
  • eventType is 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 same carId, 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

  1. Peak count. Return the largest number of cars that are inside the garage at the same moment.
  2. 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.
  3. 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 time x satisfies entryTime < 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.