Chat app~35 min2s · 256 MBtarget O(m log m) time, O(m) spaceclassic twin: lc-2097dfs · traversal
A messaging service relays a message through shards. Each logged hop is a pair [from, to]. In one long relay, every logged hop happened exactly once, and each hop started at the shard where the previous hop ended.
The log was shuffled, and nobody noted the first shard. Put the hops back in order. A valid order always exists, and you return the smallest one, comparing hop by hop.
Write arrange_hops(hops).
hops[i] is [a, b]: a hop from shard a to shard b. A hop may repeat, and a may equal b.Input: hops = [[40,7],[7,15],[15,40],[40,3],[3,7]]
Output: [[40,3],[3,7],[7,15],[15,40],[40,7]]Shard 40 sends two hops and receives one, so the relay starts there. Shard 7 receives two hops and sends one, so it is the end.
The solution gives every shard id an index, then walks with a stack. It always takes the smallest unused exit, and it moves a shard to the path when it has no exit left. Shard ids stand in the table.
| Step | Stack after the step | Path so far (backwards) |
|---|---|---|
| 1 | 40, 3 | - |
| 2 | 40, 3, 7 | - |
| 3 | 40, 3, 7, 15 | - |
| 4 | 40, 3, 7, 15, 40 | - |
| 5 | 40, 3, 7, 15, 40, 7 | - |
| 6 | 40, 3, 7, 15, 40 | 7 |
| 7 | 40, 3, 7, 15 | 7, 40 |
| 8 | 40, 3, 7 | 7, 40, 15 |
| 9 | 40, 3 | 7, 40, 15, 7 |
| 10 | 40 | 7, 40, 15, 7, 3 |
| 11 | 7, 40, 15, 7, 3, 40 |
The path reads backwards as 40, 3, 7, 15, 40, 7. Pairing neighbours gives the five hops in order.
Input: hops = [[8,2],[2,8]]
Output: [[2,8],[8,2]]Every shard sends as many hops as it receives, so the relay may start anywhere. The smallest start is shard 2.
Input: hops = [[6,6]]
Output: [[6,6]]A single hop from a shard to itself is a relay of one hop.
1 ≤ hops.length ≤ 100,000[a, b] with 0 ≤ a, b ≤ 1,000,000,000A shard id up to 10^9 cannot index a table, so the ids are sorted and numbered first, which costs O(m log m). Trying each start and backing out of dead ends can rescan every hop at each step, about m × m = 10^10 steps for m = 100,000. The stack walk uses each hop once.