Parcel-delivery app~20 min2s · 256 MBtarget O(h) time, O(1) spaceclassic twin: lc-1650tree-recursion
A parcel network has hubs in a tree. Each hub knows only the hub above it, its parent, and the top hub has none.
Two parcels are on their way up the network from two hubs. Operations wants the lowest hub that both routes pass through, so the parcels can be merged there.
The network can hold 100,000 hubs and can be a chain. Your team lead does not want a list of every hub's children built first.
Write lowest_shared_hub(parents, p, q).
0 to n - 1. parents[i] is the hub above hub i, and parents[i] is -1 for the top hub.p and q are two different hubs.p up to the top and on the route from q up to the top. A hub is on its own route.Input: parents = [-1, 0, 0, 1, 1, 2, 4, 4, 5], p = 6, q = 7
Output: 4Hubs 6 and 7 are both children of hub 4. Both are 3 links below the top, so they are lifted together.
| Stage | p | q | Depth of p | Depth of q |
|---|---|---|---|---|
| start | 6 | 7 | 3 | 3 |
| lift both | 4 | 4 | 2 | 2 |
One joint lift reaches hub 4, and the two climbs meet.
Input: parents = [-1, 0, 0, 1, 1, 2, 4, 4, 5], p = 6, q = 8
Output: 0The routes meet at the top hub.
Input: parents = [-1, 0, 0, 1, 1, 2, 4, 4, 5], p = 3, q = 1
Output: 1Hub 1 is on the route of hub 3, so it is the answer.
2 ≤ length of parents ≤ 10^5parents[0] = -1, and every other entry is a hub number from 0 to n - 10p and q are different hubs from 0 to n - 1The network can be a chain of 100,000 hubs, so a route can be 99,999 links long. Putting a whole route in a list and looking hubs up in it costs about n^2 / 2 steps on a chain, or 5 x 10^9.
Count the depth of each hub with one climb, then lift the lower one. No list is built, and the extra memory is a few variables.