We are given two arrays nums and index. We need to create a target array under the following conditions:
nums array one element at a time along with the corresponding element in the index array.nums, we insert it at the position specified in the corresponding element in index.Finally, we need to return the target array.
Example:
Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
Constraints:
nums is an array with distinct integers.index has the same length as nums.index are valid indices of the target array when elements are inserted progressively.index is within the valid range of the current target array’s length?
nums and index arrays)?
We can iterate over the elements of nums and index. For each element in nums, we use the corresponding index to determine where to insert the element in the target array. Python’s list insert method will be used for this purpose, as it handles the insertion of an element at a specified position directly.
Here is the step-by-step strategy:
nums and index together.(num, idx), use the insert method to insert num at position idx in the target array.def createTargetArray(nums, index):
target = []
for num, idx in zip(nums, index):
target.insert(idx, num)
return target
The time complexity of the insert method in a list is O(n) in the worst case, because elements might need to be shifted to make room for the new element. Given this, if we are inserting n elements one by one, the overall time complexity will be:
This is acceptable within reason for smaller value ranges of nums and index, as typically posed in coding interview problems.
Let’s run through the provided example:
# Test the function with the given example
nums = [0, 1, 2, 3, 4]
index = [0, 1, 2, 2, 1]
print(createTargetArray(nums, index)) # Output should be [0, 4, 1, 3, 2]
This completes the problem-solving process for the given task.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?