Create Target Array in the Given Order
EasyPrompt
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
Approaches
2 approaches with complexity analysis and trade-offs.
This approach directly simulates the insertion process using a standard fixed-size array. Since inserting into the middle of a primitive array is not a built-in operation, we must manually implement the logic to shift elements to the right to create a space for each new element. We iterate through the given nums and index arrays, and for each pair, we perform the shift-and-insert operation on our target array.
Algorithm
- Create a result array
targetof sizen, wherenis the length of the input arrays. - Initialize a variable
sizeto 0, which will keep track of the number of elements currently in thetargetarray. - Iterate through the input arrays from
i = 0ton-1:- Get the value
nums[i]and the insertion indexindex[i]. - To make space for the new element at
index[i], shift all elements from that index to the current end of the array (size - 1) one position to the right. This must be done in reverse order (from right to left) to avoid overwriting data. - Insert
nums[i]atindex[i]. - Increment the
sizeof the array.
- Get the value
- After the loop completes, return the
targetarray.
Walkthrough
We initialize a target array with the final required size. We also use a size variable to track how many elements have been inserted so far. For each element nums[i] to be inserted at index[i], we first shift all elements from index[i] up to the current end of the populated part of the array (size - 1) one step to the right. This opens up a spot at index[i], where we can then place nums[i]. This process is repeated for all elements.
class Solution { public int[] createTargetArray(int[] nums, int[] index) { int n = nums.length; int[] target = new int[n]; int size = 0; // current number of elements in target for (int i = 0; i < n; i++) { int idx = index[i]; int val = nums[i]; // Shift elements to the right to make space for the new element // We shift elements from the current end (size-1) down to idx for (int j = size; j > idx; j--) { target[j] = target[j - 1]; } // Insert the new element at the specified index target[idx] = val; // Increment the size of the populated part of the array size++; } return target; }}Complexity
Time
O(N^2), where N is the number of elements. The outer loop runs N times. In each iteration `i`, the inner loop for shifting can run up to `i` times in the worst case (when `index[i]` is 0). The total number of operations is proportional to the sum 1 + 2 + ... + (N-1), which is O(N^2).
Space
O(N) to store the target array. If the space for the output is not considered, the space complexity is O(1).
Trade-offs
Pros
Works with a primitive array, avoiding the overhead of wrapper classes like
Integerused inArrayList.Uses O(1) extra space if the output array is not counted as extra space.
Cons
The manual implementation of shifting elements is more verbose and prone to off-by-one errors compared to using a library class.
The code is less readable and less expressive of the high-level intent.
A more idiomatic and cleaner approach in Java is to use a dynamic array, such as ArrayList. The ArrayList class provides a convenient add(index, element) method that handles the underlying element shifting automatically. We can simply iterate through the input arrays and call this method to build the target list. Finally, we convert the ArrayList of Integer objects back to a primitive int[] array before returning.
Algorithm
- Initialize an empty
ArrayList<Integer>which will act as ourtargetarray. - Loop through the input arrays
numsandindexfromi = 0tonums.length - 1. - In each iteration, use the
ArrayList.add(index, element)method to insertnums[i]at the positionindex[i]. - After the loop, the
ArrayListcontains all the elements in the desired order. - Create a new primitive array
int[]of the same size. - Copy the elements from the
ArrayListto theint[]array. - Return the resulting
int[]array.
Walkthrough
This method leverages Java's collections framework to simplify the implementation. We use an ArrayList because it's a resizable array that allows for efficient addition of elements at the end and provides a method for insertion at any arbitrary index. While insertion in the middle of an ArrayList is not an O(1) operation (it requires shifting subsequent elements), it abstracts away the manual shifting logic, leading to cleaner and more maintainable code.
import java.util.ArrayList;import java.util.List; class Solution { public int[] createTargetArray(int[] nums, int[] index) { // Use ArrayList for its dynamic size and convenient add(index, element) method. List<Integer> targetList = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { targetList.add(index[i], nums[i]); } // Convert the List<Integer> back to an int[] array for the result. int[] targetArray = new int[nums.length]; for (int i = 0; i < targetList.size(); i++) { targetArray[i] = targetList.get(i); } return targetArray; }}Complexity
Time
O(N^2). The main loop runs N times. The `targetList.add(index[i], nums[i])` operation takes time proportional to the number of elements that need to be shifted, which is `list.size() - index[i]`. In the worst-case scenario (inserting at the beginning), this takes O(k) time at step `k`. The total time complexity is the sum of `k` for `k` from 0 to N-1, resulting in O(N^2).
Space
O(N) to store the elements in the `ArrayList`. An additional O(N) is required for the final `int[]` array.
Trade-offs
Pros
The code is simple, concise, and highly readable.
It directly maps the problem description to the
ArrayList.addmethod, reducing the chance of implementation errors.Leverages optimized native code (
System.arraycopy) for shifting elements within theArrayList.
Cons
Has the same quadratic time complexity as the manual shifting approach.
Incurs some overhead due to the use of the
ArrayListclass andIntegerwrapper objects, though this is often negligible.
Solutions
Solution
class Solution {public int[] createTargetArray(int[] nums, int[] index) { int n = nums.length; List<Integer> target = new ArrayList<>(); for (int i = 0; i < n; ++i) { target.add(index[i], nums[i]); }class Solution {public: vector<int> createTargetArray(vector<int> &nums, vector<int> &index) { vector<int> target; for (int i = 0; i < nums.size(); ++i) { target.insert(target.begin() + index[i], nums[i]); } return target; }};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) return targetVideo walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.