Ride-hailing app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-310topological-sort
A ride-hailing app serves a region of zones zones, joined by two-way roads. There are exactly zones - 1 roads, and every zone can reach every other zone. So the roads form a tree.
The app wants to open one dispatch hub in a zone. A hub's reach is the number of roads between the hub and the zone that is farthest from it. Your team lead asks: which zones give the smallest reach?
Write best_hubs(zones, roads).
0 to zones - 1. roads[i] is a pair [a, b]: a two-way road between zones a and b.Input: zones = 8, roads = [[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [2, 6], [6, 7]]
Output: [2]The roads give zone 1 the neighbours 0, 2 and 5. Zone 2 has the neighbours 1, 3 and 6. A path of zones runs 3, 4 off zone 2, and 6, 7 off zone 2 as well.
Peel the tree from the outside. Remove every zone with only one road, again and again, until one or two zones are left. Those are the best hubs.
| Round | Zones left | Zones removed | Zones with one road afterwards |
|---|---|---|---|
| 1 | 8 | 0, 4, 5, 7 |
3, 1, 6 |
| 2 | 4 | 3, 1, 6 |
2 |
| end | 1 | 2 is the answer |
Zone 2 has reach 2. Every other zone has a reach of at least 3.
Input: zones = 4, roads = [[0, 1], [1, 2], [2, 3]]
Output: [1, 2]On a line of four zones, the two middle zones both have reach 2. The ends have reach 3.
Input: zones = 1, roads = []
Output: [0]A single zone is its own hub, with reach 0.
1 ≤ zones ≤ 10^5roads has exactly zones - 1 pairs, and each number is a zone from 0 to zones - 1Measuring the reach of every zone with a search from it costs n steps per zone, about 10^10 in all. That is far too slow.
The answer is the middle of the longest path, so one linear pass is enough. The roads are an edge list, so build neighbour lists first. A long line of zones also makes any recursion 100,000 deep, so use loops and queues.