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)

๐ŸŽฌ Watch Explanation

๐Ÿ“Ž Resources