Music streaming app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1372tree-recursion
A streaming app offers an interactive show. Every scene ends with at most two buttons, Left and Right, and each button leads to a new scene. Scene 0 is the first scene, and no scene can be reached in two ways.
A viewer can start watching at any scene. Your team lead wants the longest run of choices in which the viewer alternates buttons. That is a Left, then a Right, then a Left, and so on, or the other way round.
Write longest_alternating_route(left, right).
0 to n - 1. There is at least one scene.left[i] is the scene that the Left button of scene i leads to, and right[i] the scene of its Right button. Either is -1 where there is no such button.Left comes a Right, and after a Right comes a Left. It may stop at any time.Input: left = [-1, -1, 3, -1, 5, -1, -1], right = [1, 2, -1, 4, -1, 6, -1]
Output: 5Scene 0 has only a Right button, to scene 1. Scene 1 has Right to 2, and scene 2 has Left to 3.
Scene 3 has Right to 4, scene 4 has Left to 5, and scene 5 has Right to 6.
Work from the bottom up. For every scene keep two numbers: the longest route that starts with Left, and the longest that starts with Right. Starting with Left is one choice, plus the longest route of the next scene that starts with Right. Starting with Right is one choice, plus the longest route of the next scene that starts with Left.
| Scene | Starts with Left |
Starts with Right |
|---|---|---|
6 |
0 | 0 |
5 |
0 | 1 |
4 |
2 | 0 |
3 |
0 | 3 |
2 |
4 | 0 |
1 |
0 | 5 |
0 |
0 | 1 |
The best route starts at scene 1: Right, Left, Right, Left, Right. It does not start at scene 0, whose route stops after one choice.
Input: left = [1, -1], right = [-1, -1]
Output: 1One button, so one choice.
Input: left = [-1], right = [-1]
Output: 0A scene with no buttons gives a route with no choices.
1 ≤ length of left = length of right ≤ 10^5left and right is -1 or a scene number from 1 to n - 10There are 100,000 possible starting scenes and two first buttons. Following a route from each start is fast on a bushy show. On a long chain it repeats the same walk from every start, about 5 x 10^9 steps in all.
A chain of 100,000 scenes also makes nested calls 100,000 deep, more than Python allows by default. Use a loop over a list of the scenes. The answer is below n, so a 32-bit integer holds it.