Build Array from Permutation
Problem
Given a 0-indexed permutation nums of length n, return ans where ans[i] = nums[nums[i]].
Input
nums = [0,2,1,5,3,4]Output
[0,1,2,4,5,3]ans[3] = nums[nums[3]] = nums[5] = 4.
def build_array(nums):
return [nums[nums[i]] for i in range(len(nums))]
function buildArray(nums) {
return nums.map((_, i) => nums[nums[i]]);
}
class Solution {
public int[] buildArray(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
for (int i = 0; i < n; i++) ans[i] = nums[nums[i]];
return ans;
}
}
vector<int> buildArray(vector<int>& nums) {
int n = nums.size();
vector<int> ans(n);
for (int i = 0; i < n; i++) ans[i] = nums[nums[i]];
return ans;
}
Explanation
This problem is a direct translation of the formula ans[i] = nums[nums[i]] into code. There is no clever trick — you just do a double lookup for every position.
For each index i, first read the inner value nums[i], then use that as an index back into nums to get nums[nums[i]]. Store that in the answer array at position i.
It works cleanly because nums is a permutation of 0..n-1, so every value nums[i] is itself a valid index and the second lookup never goes out of bounds.
Example: nums = [0, 2, 1, 5, 3, 4]. For i = 3, nums[3] = 5, then nums[5] = 4, so ans[3] = 4. Doing this for every index gives [0, 1, 2, 4, 5, 3].