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
Build Array from PermutationInput Array (nums):021534i=0i=1i=2i=3i=4i=5ans[i] = nums[nums[i]]nums[0]=0nums[2]=1Output Array (ans):012453Result: [0,1,2,4,5,3]
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
Asked in
LeetCode 15 Google 8
60.9K Views
Medium Frequency
~5 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen