Build Array from Permutation
Given a zero-based permutation nums (each value from 0 to nums.length - 1 appears exactly once), build a new array ans of the same length where ansi = nums[numsi] . Return the array ans, computing each position by using nums itself as a lookup table , twice in a row.
Constraints
- 1 ≤ nums.length ≤ 1000
- 0 ≤ numsi < nums.length
- The elements in nums are distinct
Example
nums = [0, 2, 1, 5, 3, 4][0, 1, 2, 4, 5, 3]Explanation ans0 = nums[nums0] = nums0 = 0, ans1 = nums[nums1] = nums2 = 1, and so on.
In plain terms
- Lookup table
- A collection where you use a value as a position to instantly find another value, instead of searching for it.
Look up nums[i] then look that result up again in nums
i=1: nums[1]=2, then nums[2]=1. ans[1]=1.
What happens in this step
i = 1 nums[1] = 2 nums[nums[1]] = nums[2] = 1 ans[1] = 1
Steps to visualize
- For each index i, first read the value numsi.
- Use that value as a new index back into nums to get nums[numsi].
- Store that result at ansi.
- Repeat for every index to build the full ans array.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
i=1: nums[1]=2, then nums[2]=1. ans[1]=1.
What happens in this step
i = 1 nums[1] = 2 nums[nums[1]] = nums[2] = 1 ans[1] = 1
Solution
function buildArray(nums) {
const ans = new Array(nums.length);
for (let i = 0; i < nums.length; i++) {
ans[i] = nums[nums[i]];
}
return ans;
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [0, 2, 1, 5, 3, 4] | [0, 1, 2, 4, 5, 3] | example from the docstring |
nums = [5, 0, 1, 2, 3, 4] | [4, 5, 0, 1, 2, 3] | a rotated permutation |
nums = [0] | [0] | smallest valid input, a single element mapping to itself |
nums = [1, 0] | [0, 1] | boundary case, exactly two elements swapped |
nums = [0, 1, 2, 3] | [0, 1, 2, 3] | the identity permutation, every value maps to itself |
nums = [3, 2, 1, 0] | [0, 1, 2, 3] | a fully reversed permutation |