Average speed at a point on a road with overlapping reports
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) -> intrecords a report and returns a unique id for it.0 <= start < end <= 10^9 + 1. -
remove(report_id: int) -> Noneremoves a report added earlier. Removing an unknown or already removed id is an error. -
query(position: int) -> floatreturns the average speed atposition: the mean of the speeds of all active reports that cover it. If no report covers it, return0.0.
The average is a plain mean over reports, not weighted by segment length.
Constraints
- Up to
10^5calls 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
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.