Music streaming app~18 min2s · 256 MBtarget O(n) time, O(n) spacetraversal
A live-show app moves guests between seats. A list moves names, for each seat, the seat its guest moves to when an announcement is made. Every seat is named exactly once, so no two guests land in the same seat.
A long show repeats the same announcement round after round. The app must say where the guest who started in each seat ends up.
Write apply_seats(moves, rounds).
moves[i] is the seat that the guest in seat i moves to in one round. Every seat from 0 to n - 1 appears once in moves.rounds rounds, a guest who started in seat i sits in some seat.result where result[i] is the final seat of the guest who started in seat i.Input: moves = [2, 0, 1, 4, 3], rounds = 2
Output: [1, 2, 0, 3, 4]Follow the seats round a cycle: seat 0 goes to 2, seat 2 goes to 1, seat 1 goes back to 0. Seats 3 and 4 swap.
| Cycle | Length | rounds mod length | Final seats |
|---|---|---|---|
| 0, 2, 1 | 3 | 2 | guest 0 to seat 1, guest 2 to seat 0, guest 1 to seat 2 |
| 3, 4 | 2 | 0 | guest 3 to seat 3, guest 4 to seat 4 |
With 2 rounds this is result[i] = moves[moves[i]], as in LeetCode 1920: Build Array from Permutation.
Input: moves = [0], rounds = 5
Output: [0]The only guest stays in the only seat.
Input: moves = [1, 0], rounds = 3
Output: [1, 0]Two guests swap seats each round. After 3 rounds, they are swapped.
1 ≤ moves.length ≤ 100,000 (seats)0 ≤ moves[i] < moves.length, and every seat appears exactly once1 ≤ rounds ≤ 1,000,000 (repeated announcements)Repeating one round costs n moves, and there can be 10^6 rounds: 10^11 moves at n = 100,000. The guests move round cycles, so after rounds rounds a guest has moved rounds mod (cycle length) steps round its own cycle. That needs one visit to each seat.