← Questions

Garage occupancy at every timestamp

0
WaymoCoding

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 n be 0 with no tickets (answer [])?
  • Are tickets guaranteed valid (entry <= exit within 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: +1 at entry, -1 at exit + 1 (skipped when that is n), 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

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding