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
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
โ Linear Growth
Space Complexity
O(n)
We need additional space for the result array
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 1000
- 0 โค nums[i] < nums.length
- nums is a permutation of integers in range [0, nums.length - 1]
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code