#1389

Create Target Array in the Given Order

Easy
ArraySimulationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal approach leverages a simple array to directly place elements in their final positions without needing to shift elements repeatedly. This is more efficient as it avoids the overhead of multiple insertions.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a target array of the same length as nums filled with zeros.
  2. 2Step 2: For each element in nums, place it directly in the target array at the index specified by the corresponding element in index.
  3. 3Step 3: Use a loop to shift elements to the right only when necessary, ensuring the target array is built correctly.
solution.py9 lines
1# Full working Python code
2
3def createTargetArray(nums, index):
4    target = [0] * len(nums)
5    for i in range(len(nums)):
6        for j in range(i, index[i], -1):
7            target[j] = target[j - 1]
8        target[index[i]] = nums[i]
9    return target

Complexity note: The time complexity remains O(n²) due to the nested loop structure, but we avoid the overhead of dynamic array resizing. The space complexity is O(n) because we create a new target array.

  • 1The insertion process requires careful management of indices.
  • 2Understanding how to manipulate arrays is crucial for this problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.