Build Array from Permutation - Problem
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 (inclusive).
Input & Output
Example 1 — Basic Permutation
$
Input:
nums = [0,2,1,5,3,4]
›
Output:
[0,1,2,4,5,3]
💡 Note:
ans[0] = nums[nums[0]] = nums[0] = 0, ans[1] = nums[nums[1]] = nums[2] = 1, ans[2] = nums[nums[2]] = nums[1] = 2, and so on.
Example 2 — Simple Case
$
Input:
nums = [5,0,1,2,3,4]
›
Output:
[4,5,0,1,2,3]
💡 Note:
ans[0] = nums[5] = 4, ans[1] = nums[0] = 5, ans[2] = nums[1] = 0, creating a shifted pattern.
Example 3 — Minimum Size
$
Input:
nums = [0]
›
Output:
[0]
💡 Note:
Single element case: ans[0] = nums[nums[0]] = nums[0] = 0.
Constraints
- 1 ≤ nums.length ≤ 1000
- 0 ≤ nums[i] < nums.length
- The elements in nums are distinct.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Permutation array [0,2,1,5,3,4]
2
Transform
For each i, calculate nums[nums[i]]
3
Output
New array [0,1,2,4,5,3]
Key Takeaway
🎯 Key Insight: Use each element's value as an index to look up the transformation value
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code