Music streaming app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-662bfs
A streaming app shows a live knockout bracket. Each match is decided between at most two earlier matches, a left one and a right one, and the final is the top match. The bracket is drawn as a full tree, so a match with a missing earlier match leaves an empty slot.
Your team lead needs the widest round, to size the screen. The width of a round is the number of slots from its leftmost match to its rightmost match, counting the empty slots between them.
Write widest_round(left, right).
0 to n - 1, and match 0 is the final. An empty bracket has two empty lists.left[i] and right[i] are the numbers of the earlier matches that feed match i, or -1 where there is none.p is at 2p in the next round, and the right one is at 2p + 1.0. It is guaranteed that no round is wider than 10^9.Input: left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1]
Output: 5Match 0 is fed by 1 and 2. Match 1 is fed by 3 and 4. Match 2 is fed only by a right match 5.
Match 4 is fed by 6 and 7. Match 5 is fed only by a left match 8.
Each match gets a position inside its round, counted from the leftmost match of that round as 0. The matches in round 3 are 3, 4 and 5 at the positions 0, 1 and 3: the slot 2 is empty.
| Round | Matches (positions) | First position | Width: last - first + 1 |
|---|---|---|---|
| 1 | 0 (0) |
0 | 1 |
| 2 | 1 (0), 2 (1) |
0 | 2 |
| 3 | 3 (0), 4 (1), 5 (3) |
0 | 4 |
| 4 | 6 (2), 7 (3), 8 (6) |
2 | 5 |
Round 3 has 3 matches but a width of 4, because of the empty slot. Round 4 also has 3 matches, and a width of 5. The answer is 5.
Input: left = [1, 2, -1], right = [-1, -1, -1]
Output: 1A chain: each round has one match.
Input: left = [], right = []
Output: 00 ≤ length of left = length of right ≤ 10^5left and right is -1 or a match number from 1 to n - 1010^9 slotsA bracket can be a chain 100,000 rounds deep. Drawing every round as a list of all its slots doubles the list each round, so it breaks after about 25 rounds.
Positions in a full tree double at every round too. After about 63 rounds they no longer fit in a 64-bit integer, and in JavaScript they lose precision after 53. Count each position from the leftmost match of its round, which keeps every number below about 2 x 10^9. The width is returned as a long.