Create Target Array in the Given Order - Problem
Given two arrays of integers nums and index, your task is to dynamically build a target array by following a series of insertion operations.
Here's how it works:
- Start with an empty target array
- For each position
ifrom left to right, insert the valuenums[i]at positionindex[i]in the target array - When you insert at a position, all existing elements at that position and beyond shift to the right
- Continue until all elements are processed
Example: If nums = [0,1,2,3,4] and index = [0,1,2,2,1], you would:
- Insert 0 at position 0:
[0] - Insert 1 at position 1:
[0,1] - Insert 2 at position 2:
[0,1,2] - Insert 3 at position 2:
[0,1,3,2](2 shifts right) - Insert 4 at position 1:
[0,4,1,3,2](1,3,2 shift right)
Return the final target array after all insertions.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [0,1,2,3,4], index = [0,1,2,2,1]
โบ
Output:
[0,4,1,3,2]
๐ก Note:
Step by step: [] โ [0] โ [0,1] โ [0,1,2] โ [0,1,3,2] โ [0,4,1,3,2]. Each insertion shifts existing elements at that position to the right.
example_2.py โ Simple Sequential
$
Input:
nums = [1,2,3,4,0], index = [0,1,2,3,0]
โบ
Output:
[0,1,2,3,4]
๐ก Note:
Most insertions are at the end, except the last one inserts 0 at the beginning, shifting all elements right: [1] โ [1,2] โ [1,2,3] โ [1,2,3,4] โ [0,1,2,3,4].
example_3.py โ Single Element
$
Input:
nums = [1], index = [0]
โบ
Output:
[1]
๐ก Note:
With only one element, we simply insert it at index 0 in the empty array, resulting in [1].
Constraints
- 1 โค nums.length, index.length โค 100
- nums.length == index.length
- 0 โค nums[i] โค 100
- 0 โค index[i] โค i
- All insertion operations are guaranteed to be valid
Visualization
Tap to expand
Understanding the Visualization
1
Empty Theater
Start with an empty row of seats (empty array)
2
First Guest Arrives
Person wants seat 0, sits down immediately
3
Second Guest
Person wants seat 1, sits next to the first person
4
Disruption!
New person wants seat 1 - everyone from seat 1 onwards shifts right
5
Final Arrangement
All guests are seated according to their arrival order and preferences
Key Takeaway
๐ฏ Key Insight: This problem is fundamentally about simulation - we need to replicate the exact insertion process. The 'brute force' approach of using built-in insertion operations is actually optimal because it naturally handles the complex shifting logic for us.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code