Create Target Array in the Given Order

You are given two arrays nums and index. You have to create a target array by inserting the elements from nums at the positions specified by index.

Approach

  1. Initialize an empty target list.
  2. Iterate through nums and index simultaneously using a loop.
  3. Use the insert() method to insert the element nums[i] at position index[i] in the target list.
  4. Continue until all elements from nums are processed.
  5. Return the target list.

Here’s the code implementing this approach:

1
2
3
4
5
6
class Solution:
    def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
        target = []
        for i in range(len(nums)):
            target.insert(index[i], nums[i])
        return target

Example

Let’s take nums = [0,1,2,3,4] and index = [0,1,2,2,1] as an example:

  • Insert 0 at index 0: target = [0]
  • Insert 1 at index 1: target = [0,1]
  • Insert 2 at index 2: target = [0,1,2]
  • Insert 3 at index 2: target = [0,1,3,2]
  • Insert 4 at index 1: target = [0,4,1,3,2]

So the output will be [0,4,1,3,2].

This solution is simple and easy to understand for beginners. It directly implements the instructions given in the problem statement, using the insert() method provided by Python’s list class.