Create Target Array in the Given Order Problem
Description
LeetCode Problem 1389.
Given two arrays of integers nums and index. Your task is to create target array under the following rules:
- Initially target array is empty.
- From left to right read nums[i] and index[i], insert at index
index[i]the valuenums[i]in target array. - Repeat the previous step until there are no elements to read in
numsandindex.
Return the target array.
It is guaranteed that the insertion operations will be valid.
Example 1:
Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
Explanation:
nums index target
0 0 [0]
1 1 [0,1]
2 2 [0,1,2]
3 2 [0,1,3,2]
4 1 [0,4,1,3,2]
Example 2:
Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
Output: [0,1,2,3,4]
Explanation:
nums index target
1 0 [1]
2 1 [1,2]
3 2 [1,2,3]
4 3 [1,2,3,4]
0 0 [0,1,2,3,4]
Example 3:
Input: nums = [1], index = [0]
Output: [1]
Constraints:
1 <= nums.length, index.length <= 100nums.length == index.length0 <= nums[i] <= 1000 <= index[i] <= i
Solution
Approach: Simulate the Insertions
The rules describe exactly what to do, and the arrays are short (at most 100 elements), so we can simply carry them out.
Start with an empty list target. For each i from left to right, insert nums[i] at position index[i]. An insertion in the middle shifts every element from that position onward one step to the right, which is what the problem means by "insert". The guarantee index[i] <= i says the position always exists: before step i the list holds exactly i elements, so index[i] == i appends at the end.
Every language has a built-in for this: list.insert in Python, List.add(index, value) in Java, vector::insert in C++ and splice in JavaScript. In Go we grow the slice by one, shift the tail with copy, then write the new value.
Complexity: O(n2) time, since each insertion can shift up to n elements, and O(n) space for the result.
class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
target = []
for x, i in zip(nums, index):
target.insert(i, x) # shifts everything from position i one step right
return target