Build Array from Permutation - Problem

You're given a special array called a zero-based permutation - an array containing each integer from 0 to n-1 exactly once, where n is the array length.

Your task is to transform this permutation into a new array using a simple rule: for each position i, the new value should be nums[nums[i]]. In other words, use the value at position i as an index to look up another value in the original array.

Example: If nums = [0,2,1,5,3,4], then:

  • Position 0: nums[nums[0]] = nums[0] = 0
  • Position 1: nums[nums[1]] = nums[2] = 1
  • Position 2: nums[nums[2]] = nums[1] = 2

This creates a double lookup pattern that's common in array manipulation problems!

Input & Output

example_1.py โ€” Basic Permutation
$ Input: [0,2,1,5,3,4]
โ€บ Output: [0,1,2,4,5,3]
๐Ÿ’ก Note: At index 0: nums[nums[0]] = nums[0] = 0. At index 1: nums[nums[1]] = nums[2] = 1. At index 2: nums[nums[2]] = nums[1] = 2. Continuing this pattern gives us [0,1,2,4,5,3].
example_2.py โ€” Small Array
$ Input: [5,0,1,2,3,4]
โ€บ Output: [4,5,0,1,2,3]
๐Ÿ’ก Note: Each element points to the next position in a circular fashion. nums[0]=5 so ans[0]=nums[5]=4, nums[1]=0 so ans[1]=nums[0]=5, and so on.
example_3.py โ€” Single Element
$ Input: [0]
โ€บ Output: [0]
๐Ÿ’ก Note: With only one element, nums[0] = 0, so ans[0] = nums[nums[0]] = nums[0] = 0. The array remains unchanged.

Visualization

Tap to expand
Double Lookup Process: nums[nums[i]]2Position 1Clue: 21Position 2Treasure: 11Result[1]Store: 1Follow clueTake treasureComplete Example: nums = [0,2,1,5,3,4]Position 0: clue=0 โ†’ treasure=nums[0]=0 โ†’ result[0]=0Position 1: clue=2 โ†’ treasure=nums[2]=1 โ†’ result[1]=1Position 2: clue=1 โ†’ treasure=nums[1]=2 โ†’ result[2]=2Final result: [0,1,2,4,5,3]
Understanding the Visualization
1
Read the Clue
At position i, read the value nums[i] which tells us which position to look at next
2
Follow the Clue
Go to position nums[i] and read the treasure value nums[nums[i]]
3
Store the Treasure
Place the treasure value in the result array at position i
Key Takeaway
๐ŸŽฏ Key Insight: Since it's a permutation, every 'clue' (nums[i]) points to a valid position, making the double lookup safe and straightforward!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

We visit each element exactly once to perform the lookup

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

We need additional space for the result array

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • 0 โ‰ค nums[i] < nums.length
  • nums is a permutation of integers in range [0, nums.length - 1]
Asked in
Amazon 15 Google 8 Meta 5 Microsoft 3
45.0K Views
High Frequency
~8 min Avg. Time
1.5K 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