Build Array from Permutation(#1920)
Category: Array, Foundation
๐งฉ Problem Statement
You're given a zero-based permutation array nums (which means the array contains all distinct numbers from 0 to nums.length - 1). You need to build a new array ans of the same length where: ans[i] = nums[nums[i]] for each 0 <= i < nums.length.
๐ Examples
Input: nums = [0,2,1,5,3,4]
Output: [0,1,2,4,5,3]
Explanation: For each index i, we assign ans[i] = nums[nums[i]].
Input: nums = [5,0,1,2,3,4]
Output: [4,5,0,1,2,3]
Explanation: Same logic applies โ lookup nums[nums[i]] for each i.
๐ง Approach
โข Initialize an empty array `ans`.
โข Loop from 0 to nums.length - 1.
โข Set ans[i] = nums[nums[i]].
โข Return ans.
This is a direct implementation of the problem statement and keeps things simple.
๐ป Code
var buildArray = function(nums) {
let ans = [];
for (let i = 0; i < nums.length; i++) {
ans[i] = nums[nums[i]];
}
return ans;
};
๐ Complexity
Time: O(n)
Space: O(n)