Ctrl K

Two Hops Along the Links

Easy
There are n cells in a row, numbered 0 to n - 1. Cell i holds a note with a cell number links[i]. All the notes are different, so every cell is mentioned exactly once. For every cell i, work out where you end up after two hops: first follow the note in i, then follow the note in the cell you landed on. Return a list of length n whose entry i is the cell you finish in. Bonus: can you do it with no extra memory by writing the answer back into links?
Example 1
links=[2, 0, 1] → [1, 2, 0]

From 0 we go to 2, then to 1; from 1 to 0, then to 2; from 2 to 1, then to 0. That gives [1, 2, 0].

Example 2
links=[1, 0, 3, 2] → [0, 1, 2, 3]

The cells form pairs pointing at each other, so two hops always bring you back to where you started.

Example 3
links=[0] → [0]
Constraints
  • 1 ≤ len(links) ≤ 1000
  • 0 ≤ links[i] < len(links)
  • All values in links are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHow Long the Light Stayed On EasyRepack the Tray EasyQuiz Score Log EasyMirror and Negate a Bitmap EasySwap Rows and Columns Easy
loading Python…
Input
links=[2, 0, 1]
Expected
[1, 2, 0]

Run checks the first 3 tests in your browser. Submit checks all 80 tests on the server, hidden ones included.