← Questions

Average speed at a point on a road with overlapping reports

0
WaymoCoding

A coding interview question asked at Waymo. It tests segment tree, range update and data structure design.

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

Clarifying questions

  • Can speeds be fractional, and how exact must the average be after many adds and removes?
  • Is end exclusive, so query(end) is not covered?
  • What should remove raise for an unknown or already removed id?
  • Must add return ids that are never reused?

What a strong answer covers

  • Turns each report into two range updates: add speed and 1 to every position in [start, end); a query is the ratio of the two sums at one position.
  • Since coordinates reach 10^9 and calls arrive online, uses a dynamic segment tree (nodes created on demand) or a Fenwick-style difference structure over a sparse map, giving O(log C) per call.
  • Stores each report by id so remove applies the opposite update, and checks for unknown ids.
  • Mentions floating-point drift from repeated add and remove, and avoids it by keeping exact sums when speeds are integers.
  • Tests the example, removing every report, nested and touching segments, and a query at 10^9.

Follow-ups

  • Return the length-weighted average over a range of positions.
  • Reports expire after a time window.
  • Return the maximum speed at a position instead of the mean.

Where it's asked

What it tests

segment tree · range update · data structure design

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