You are given two integer arrays nums and index of the same length. Build a target array under these rules:
-
The target array starts empty.
-
Read
nums[i]
and
index[i]
from left to right, and insert the value
nums[i]
into the target array at position
index[i]
.
-
Repeat until every pair has been read.
Return the target array. Every insertion is guaranteed to be valid.
Function Signature
def create_target_array(nums: list[int], index: list[int]) -> list[int]:
Rules
-
Positions are 0-based.
-
Inserting at position
p
puts the new value at
p
and shifts the element that was at
p
, and every element after it, one place to the right. Nothing is overwritten.
-
Before the i-th insertion (0-based) the target holds exactly
i
elements. Since
index[i] <= i
, a value of
index[i] == i
means appending at the end.
Constraints
-
1 <= nums.length, index.length <= 100
-
nums.length == index.length
-
0 <= nums[i] <= 100
-
0 <= index[i] <= i
Examples
Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
The target grows as [0], [0,1], [0,1,2], [0,1,3,2], [0,4,1,3,2]. Inserting 3 at position 2 pushes 2 to the right, and inserting 4 at position 1 pushes 1, 3 and 2 to the right.
Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
Output: [0,1,2,3,4]
The first four values are each appended at the end, giving [1,2,3,4]. The last value 0 goes in at position 0 and shifts all four to the right.
Input: nums = [5,6,7], index = [0,0,0]
Output: [7,6,5]
Every value is inserted at the front, so each new value pushes the earlier ones right and the final order is the reverse of nums.