Music streaming app~35 min2s · 256 MBtarget O(m log m) time, O(n + m) spaceclassic twin: lc-332dfs · traversal
A music app logs every handoff from one track to the next, as a pair of track ids. During one long listening session, each logged handoff happened exactly once, and the session began at a known track.
You want to replay the session as the list of tracks that were played. Several replays may fit the log. Return the smallest one, comparing the lists track by track from the first track.
Write rebuild_session(handoffs, start).
handoffs[i] is [a, b]: one time, track a was followed by track b. A pair may repeat, and a may equal b.start and uses every handoff exactly once, each in the direction it was logged.start.Input: handoffs = [[0,1],[0,2],[2,0],[2,3],[3,2]], start = 0
Output: [0, 2, 3, 2, 0, 1]Track 0 has two exits, to 1 and to 2. Taking the smaller exit, 1, ends the session at once, with three handoffs unused. So the session must keep 1 for last.
The solution walks forward with a stack, always taking the smallest unused exit. A track with no exit left goes to the path. The path is built backwards.
| Step | Stack after the step | Path so far (backwards) |
|---|---|---|
| 1 | 0, 1 | - |
| 2 | 0 | 1 |
| 3 | 0, 2 | 1 |
| 4 | 0, 2, 0 | 1 |
| 5 | 0, 2 | 1, 0 |
| 6 | 0, 2, 3 | 1, 0 |
| 7 | 0, 2, 3, 2 | 1, 0 |
| 8 | 0, 2, 3 | 1, 0, 2 |
| 9 | 0, 2 | 1, 0, 2, 3 |
| 10 | 0 | 1, 0, 2, 3, 2 |
| 11 | 1, 0, 2, 3, 2, 0 |
Reading the path backwards gives 0, 2, 3, 2, 0, 1. It uses all five handoffs, and it is the smallest valid session.
Input: handoffs = [[0,1],[2,3]], start = 0
Output: []From track 0 the session reaches only track 1. The handoff from 2 to 3 can never be used, so no session exists.
Input: handoffs = [[1,2],[2,1]], start = 1
Output: [1, 2, 1]Track 1 leads to 2 and back. Both handoffs are used once.
0 ≤ handoffs.length ≤ 100,000, and each pair is [a, b] with 0 ≤ a, b ≤ 49,9990 ≤ start ≤ 49,999Trying the smallest exit and backing out of dead ends can rescan every handoff at each step, so it costs about m × m = 10^10 steps for m = 100,000. The stack walk uses each handoff once, and the sorting costs O(m log m), about 1.7 × 10^6 steps.