Average speed at a point on a road with overlapping reports

0
Sign in

A straight road is modeled as the number line from position 0 to 10^9. Vehicles send speed reports. Each report says that traffic on the half-open segment [start, end) moved at speed, so it covers every integer position p with start <= p < end. Reports can overlap.

Implement RoadwaySpeedTracker:

  • RoadwaySpeedTracker() creates an empty tracker.
  • add(start: int, end: int, speed: float) -> int records a report and returns a unique id for it. 0 <= start < end <= 10^9 + 1.
  • remove(report_id: int) -> None removes a report added earlier. Removing an unknown or already removed id is an error.
  • query(position: int) -> float returns the average speed at position: the mean of the speeds of all active reports that cover it. If no report covers it, return 0.0.

The average is a plain mean over reports, not weighted by segment length.

Constraints

  • Up to 10^5 calls in total, in any order.
  • Calls arrive online: you do not know future coordinates.
  • Aim for better than scanning every report on each query.

Example

t = RoadwaySpeedTracker()
a = t.add(0, 10, 60)
b = t.add(5, 15, 30)
t.query(3)   -> 60.0   # only a covers 3
t.query(5)   -> 45.0   # (60 + 30) / 2
t.query(10)  -> 30.0   # a ends at 10, which it does not cover
t.query(15)  -> 0.0    # nothing covers 15
t.remove(a)
t.query(5)   -> 30.0
WaymoCodingHard

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.