36. Index Lookup Chain

EasyArray

A scavenger hunt is laid out on a row of n stations numbered 0 to n-1. Each station i holds a note with one station number, given by nums[i], and every station number appears on exactly one note. To speed up the hunt, the organizers want a second list in which each station shows not its own note, but the note found at the station that its note points to.

Write a method buildFromIndices that takes the array nums and returns a new array ans of the same length where ans[i] = nums[nums[i]] for every i.

Example 1

Input:
nums = [0,2,1,5,3,4]
Output:
[0,1,2,4,5,3]
Explanation:

For station 3 the note says 5, and station 5 holds the note 4, so ans[3] = 4. Doing the same for every station gives [0, 1, 2, 4, 5, 3].

Example 2

Input:
nums = [5,0,1,2,3,4]
Output:
[4,5,0,1,2,3]
Explanation:

Following each note to the station it names gives [4, 5, 0, 1, 2, 3].

Constraints

1 ≤ nums.length ≤ 1000

nums is a permutation of the numbers from 0 to nums.length - 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…