In the Riverside Relay Festival, n racers are numbered 0 through n - 1, standing at fixed positions around the track. Each racer i has one designated hand-off partner, handoff[i] — the racer to whom racer i will pass the baton on their turn. Because handoff is a permutation of the racer numbers, every racer hands off to exactly one racer (possibly themself), and every racer also receives the baton from exactly one racer.
The event organizer wants to trace the baton two hand-offs ahead for every racer: starting at racer i, the baton first moves to handoff[i], and then from there to handoff[handoff[i]]. Compute this two-hop destination for every racer i.
Line 1: an integer n, the number of racers. Line 2: n space-separated integers handoff[0], handoff[1], ..., handoff[n-1] — a permutation of 0..n-1 (all values distinct and 0 <= handoff[i] < n).
Print n space-separated integers on one line: for each racer i from 0 to n-1, the racer holding the baton after two hand-offs starting from i.
1 <= n <= 1000 0 <= handoff[i] < n handoff is a permutation of 0..n-1 (all n values are distinct)
Example 1
Input
5 1 3 0 4 2
Expected
3 4 1 2 0
Explanation
handoff = [1,3,0,4,2]. For racer 0: handoff[0]=1, handoff[1]=3, so the two-hop result is 3. For racer 1: handoff[1]=3, handoff[3]=4, result 4. For racer 2: handoff[2]=0, handoff[0]=1, result 1. For racer 3: handoff[3]=4, handoff[4]=2, result 2. For racer 4: handoff[4]=2, handoff[2]=0, result 0. Output: 3 4 1 2 0.
Example 2
Input
3 2 0 1
Expected
1 2 0
Explanation
handoff = [2,0,1]. Racer 0: handoff[0]=2, handoff[2]=1, result 1. Racer 1: handoff[1]=0, handoff[0]=2, result 2. Racer 2: handoff[2]=1, handoff[1]=0, result 0. Output: 1 2 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →