Parcel-delivery app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-543tree-recursion
A parcel-delivery app links its hubs in a tree. The main hub sends to at most two hubs, each of those sends to at most two more, and so on. A parcel can travel along a link in either direction.
Your team lead wants the worst case for a handover between two hubs: the largest number of links on the way between any two hubs. The two hubs can be anywhere in the network, and the way between them need not pass through the main hub.
Write farthest_hub_links(left, right).
0 to n - 1, and hub 0 is the main hub. An empty network has two empty lists.left[i] and right[i] are the hubs that hub i sends to, or -1 where there is none.0.Input: left = [1, 2, 3, -1, -1, -1, -1], right = [-1, 4, -1, -1, 5, 6, -1]
Output: 5Hub 0 sends only to hub 1. Hub 1 sends to 2 (left) and 4 (right). Hub 2 sends to 3. Hub 4 sends to 5, and 5 sends to 6.
Work from the bottom up. The height of a hub is the number of levels below and including it. The best way through a hub joins its two sides: left height plus right height links.
| Hub | Left height | Right height | Through this hub | Best so far | Height |
|---|---|---|---|---|---|
6 |
0 | 0 | 0 | 0 | 1 |
5 |
0 | 1 | 1 | 1 | 2 |
4 |
0 | 2 | 2 | 2 | 3 |
3 |
0 | 0 | 0 | 2 | 1 |
2 |
1 | 0 | 1 | 2 | 2 |
1 |
2 | 3 | 5 | 5 | 4 |
0 |
4 | 0 | 4 | 5 | 5 |
The longest way is 3, 2, 1, 4, 5, 6: 5 links. It does not pass through hub 0.
Input: left = [-1], right = [-1]
Output: 0One hub has no other hub to travel to.
Input: left = [], right = []
Output: 00 ≤ length of left = length of right ≤ 10^5left and right is -1 or a hub number from 1 to n - 10Trying every pair of hubs costs about n^2 / 2 steps, which is billions for a network of 100,000. A chain also makes nested calls 100,000 deep, more than Python allows by default.
Look at every hub once, from the bottom up, and use a loop and a list.