Parcel-delivery app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-103bfs
A parcel-delivery app runs a sorting hub. Every belt splits into at most two belts, a left one and a right one. The belts form tiers: tier 1 is the first belt, tier 2 holds the belts it splits into, and so on.
Staff walk the hub in a snake pattern. They walk tier 1 from left to right, tier 2 from right to left, tier 3 from left to right again, and so on. Your team lead wants the belt ids in the order they are walked.
Write snake_tiers(values, left, right).
0 to n - 1, and belt 0 is the first belt. An empty hub has three empty lists.values[i] is the id printed on belt i. left[i] and right[i] are the numbers of the belts it splits into, or -1 where there is none.Input: values = [8, 3, 10, 1, 6, 14, 4, 7, 13], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1]
Output: [[8], [10, 3], [1, 6, 14], [13, 7, 4]]Belt 0 (id 8) splits into 1 (id 3) and 2 (id 10). Belt 1 splits into 3 (1) and 4 (6). Belt 2 has only a right belt 5 (14).
Belt 4 splits into 6 (4) and 7 (7). Belt 5 has only a left belt 8 (13).
The queue always keeps its normal left-to-right order. Only the place where each id is written changes on every second tier.
| Tier | Queue at the start (ids) | Direction | Row written |
|---|---|---|---|
| 1 | 8 | left to right | 8 |
| 2 | 3, 10 | right to left | 10, 3 |
| 3 | 1, 6, 14 | left to right | 1, 6, 14 |
| 4 | 4, 7, 13 | right to left | 13, 7, 4 |
Input: values = [7], left = [-1], right = [-1]
Output: [[7]]Input: values = [], left = [], right = []
Output: []0 ≤ length of values = length of left = length of right ≤ 10^50 ≤ values[i] ≤ 10^6left and right is -1 or a belt number from 1 to n - 10A hub can be one chain of 100,000 belts, which makes 100,000 tiers. Finding each tier by scanning every belt costs about n^2 steps on it.
Build each tier from the tier before it. Every belt is then looked at once.