Build Array from Permutation
Easy
Topics
Given a zero-based permutation nums, build an array ans of the same length where ans[i] = nums[nums[i]].
Example 1
nums[nums[i]] — one hop through the permutation, then another.Input: nums = [0,2,1,5,3,4] Output: [0,1,2,4,5,3]
Example 2
Input: nums = [5,0,1,2,3,4] Output: [4,5,0,1,2,3]
Constraints
- 1 <= nums.length <= 1000
- nums is a permutation of 0..n-1
Editorial — intuition, approach, complexity and pitfalls
Intuition
The task is a one-line definition: ans[i] = nums[nums[i]]. Read it inside out — take nums[i], use that as an index, and look up nums again. Because the input is a permutation of 0..n-1, every nums[i] is a valid index, so the double lookup can never go out of range.
Building a second array is the honest answer and it is O(n) space. The reason this problem exists is the follow-up: can you do it in O(1) extra space? You cannot simply overwrite in place, because nums[i] = nums[nums[i]] destroys values that later positions still need to read.
The trick is to store both the old and new value in the same slot. Since every value is below n, two values fit in one number by encoding them in different "digits" base n: keep the old value in the low part and the new one in the high part.
pass 1: nums[i] += n * (nums[nums[i]] % n)
low part = old value (unchanged, so later reads still work)
high part = new value
pass 2: nums[i] //= n keep only the new valueThe % n is essential — by the time you read nums[nums[i]] it may already have been encoded, and % n recovers its original low part regardless. The shown solution builds a new array because it is clearer; the encoding is what to reach for only if O(1) space is demanded.
Approach
- For each
i, computenums[nums[i]]and write it toans[i].
Dry Run
nums = [0, 2, 1, 5, 3, 4]
i=0: nums[0]=0 -> nums[0]=0
i=1: nums[1]=2 -> nums[2]=1
i=2: nums[2]=1 -> nums[1]=2
i=3: nums[3]=5 -> nums[5]=4
i=4: nums[4]=3 -> nums[3]=5
i=5: nums[5]=4 -> nums[4]=3
answer [0, 1, 2, 4, 5, 3]Complexity
- Time — O(n): one pass, two array reads per element.
- Space — O(n): the output array. As the result rather than scratch space it does not count as auxiliary by the usual convention, so the honest statement is O(1) auxiliary. The base-
nencoding above achieves O(1) even including the output, by reusing the input array.
Common Pitfalls
- Overwriting
numsin place without encoding.nums[i] = nums[nums[i]]corrupts values that later indices still need, and the failure is data-dependent — it passes on some permutations and not others. - Dropping the
% nin the encoded version. The inner lookup may already hold an encoded value, and without the modulus you read the wrong half. - Assuming the input might contain out-of-range values. It is a permutation of
0..n-1by constraint, which is precisely what makes the double index safe and the encoding possible. - Reaching for the encoding trick unprompted. The straightforward version is clearer; produce the trick when asked for O(1) space, and explain why in-place without it breaks.
Full Solution — all languages
class Solution:
def buildArray(self, nums):
return [nums[nums[i]] for i in range(len(nums))]import java.util.*;
class Solution {
public int[] buildArray(int[] nums) {
int[] ans = new int[nums.length];
for (int i = 0; i < nums.length; i++) ans[i] = nums[nums[i]];
return ans;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> buildArray(vector<int>& nums) {
vector<int> ans(nums.size());
for (size_t i = 0; i < nums.size(); i++) ans[i] = nums[nums[i]];
return ans;
}
};/**
* @param {number[]} nums
* @return {number[]}
*/ var buildArray = function(nums) {
return nums.map((_, i) => nums[nums[i]]);
};