Build Array from Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).

30:00

Build Array from Permutation
easy
Free written solution
Topics
Companies

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).

Example 1:
Input: {"nums":[0,2,1,5,3,4]}
Output: [0,1,2,4,5,3]
Constraints:
  • 1≤nums.length≤10001 \leq \text{nums.length} \leq 1000

  • 0≤nums[i]<nums.length0 \leq \text{nums}[i] < \text{nums.length}

  • The elements in nums are distinct.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[0,2,1,5,3,4]}

Each ans[i] takes two hops through nums: first nums[i] gives an index j, then nums[j] is the value to copy.

ans[i] = nums[nums[i]]

nums

0

0

1

2

2

1

3

5

4

3

5

4

ans

violet arrow: hop 1, i to j = nums[i]green arrow: hop 2, nums[j] copied into ans[i]
Variables
VariableValue
n6
DepthFunction Call
Stack empty
0/13