Build Array from Permutation

(#1920), Easy

Category: Array

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

Direct Index Mapping

  • Initialize an empty array `ans`.
  • Loop from `i = 0` to `nums.length - 1`.
  • At each step, assign `ans[i] = nums[nums[i]]`.
  • Return the `ans` array.
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