Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created May 6, 2025 17:29
Show Gist options
  • Save tatsuyax25/aa9856c1891b60a1da3f614f9cfb948a to your computer and use it in GitHub Desktop.
Save tatsuyax25/aa9856c1891b60a1da3f614f9cfb948a to your computer and use it in GitHub Desktop.
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1
/**
* @param {number[]} nums
* @return {number[]}
*/
var buildArray = function(nums) {
let ans = []; // Initialize an empty array to store the result
// Iterate through each index in the `nums` array
for (let i = 0; i < nums.length; i++) {
ans.push(nums[nums[i]]); // Push the element from `nums` at the index specified by `nums[i]`
}
return ans; // Return the resulting array
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment