Garage occupancy at every timestamp
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Waymo. It tests arrays, prefix sums and sweep line.
A parking garage records occupancy over n discrete timestamps, numbered 0 to n - 1. You get a list of parking tickets. Ticket [entry, exit] means one car arrived at timestamp entry and left at timestamp exit.
A car counts as present at every timestamp t with entry <= t <= exit. It still counts at its exit timestamp and stops counting at exit + 1.
Implement:
def garage_occupancy(n: int, tickets: list[list[int]]) -> list[int]:
...
Return a list of length n where position t is the number of cars in the garage at timestamp t.
Constraints
-
0 <= n <= 10^5,0 <= len(tickets) <= 10^5 0 <= entry <= exit <= n - 1- Several cars can share the same entry or exit timestamp.
Example 1
n = 5
tickets = [[0, 2], [1, 1], [2, 4]]
output = [1, 2, 2, 1, 1]
At timestamp 2, the first car is leaving and the third car is arriving. Both count, so the total is 2.
Example 2
n = 4
tickets = [[3, 3]]
output = [0, 0, 0, 1]
Aim for better than O(n * len(tickets)) time.
Clarifying questions
- Can
nbe 0 with no tickets (answer[])? - Are tickets guaranteed valid (
entry <= exitwithin range), or should I validate? - Is a car present at both its entry and exit timestamps, as stated?
What a strong answer covers
- Uses a difference array:
+1atentry,-1atexit + 1(skipped when that isn), then a running sum. - Runs in O(n + tickets) time and O(n) memory, against O(n * tickets) for filling each range.
- Gets the inclusive exit right (Example 1 counts the leaving and arriving cars at timestamp 2).
- Tests both examples, a ticket covering everything, many tickets on one timestamp and
n = 0.
Follow-ups
- Timestamps are huge and sparse: sort events and return only the change points.
- Report the peak occupancy and when it happens.
- Answer queries while tickets keep arriving (a Fenwick tree).
Where it's asked
What it tests
arrays · prefix sums · sweep line
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
