Construct a new array where each position takes its value from the index pointed to by the original array.
You are given a zero-based permutation array nums of length n, where each value in nums is an integer from 0 to n - 1 and appears exactly once.
Build a new array ans of length n such that for every index i,
ans[i] = nums[nums[i]].
Return the resulting array.
The task is a straightforward index-mapping transformation: use each value in the input array as an index into the same array and write down the referenced value in the output.
Input Format
- The input is an integer array
nums. numsis a permutation of0..n-1.- For every index
i, computeans[i] = nums[nums[i]].
Output Format
- Return an integer array
ansof the same length asnums. ans[i]must equal the value at indexnums[i]in the original array.
Constraints
1 <= n <= 1000or larger depending on platform test data.numscontains each integer from0ton - 1exactly once.- Do not assume values outside the valid index range.
Example 1
Input
nums = [0,2,1,5,3,4]
Output
[0,1,2,4,5,3]
Explanation
For each index i, take nums[nums[i]]: [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]] = [0,1,2,4,5,3].
Example 2
Input
nums = [5,0,1,2,3,4]
Output
[4,5,0,1,2,3]
Explanation
Using the same rule, ans[0]=nums[5]=4, ans[1]=nums[0]=5, ans[2]=nums[1]=0, and so on.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.