Create Target Array in the Given Order
Problem
Given two arrays nums and index of length n, build target by inserting nums[i] at target[index[i]] for i = 0..n-1.
nums = [0,1,2,3,4], index = [0,1,2,2,1][0,4,1,3,2]def create_target_array(nums, index):
target = []
for n, i in zip(nums, index):
target.insert(i, n)
return target
function createTargetArray(nums, index) {
const t = [];
for (let i = 0; i < nums.length; i++) t.splice(index[i], 0, nums[i]);
return t;
}
class Solution {
public int[] createTargetArray(int[] nums, int[] index) {
List t = new ArrayList<>();
for (int i = 0; i < nums.length; i++) t.add(index[i], nums[i]);
int[] r = new int[t.size()];
for (int i = 0; i < r.length; i++) r[i] = t.get(i);
return r;
}
}
vector createTargetArray(vector& nums, vector& index) {
vector t;
for (int i = 0; i < (int)nums.size(); i++) t.insert(t.begin() + index[i], nums[i]);
return t;
}
Explanation
This problem is really just asking you to follow the instructions exactly. You build the answer step by step by inserting each number into the spot the rules tell you to. This is called direct simulation — we mimic the described process instead of being clever.
We start with an empty list target. Then for each pair of values from nums and index, we use target.insert(i, n) to slide the number n into position i. Insert automatically shifts everything after that spot to the right to make room.
The order matters: we process the pairs left to right, and each insertion can push earlier numbers further along, which is exactly the behavior the problem wants.
Example: nums = [0,1,2,3,4], index = [0,1,2,2,1]. Insert 0 at 0 → [0]; 1 at 1 → [0,1]; 2 at 2 → [0,1,2]; 3 at 2 → [0,1,3,2]; 4 at 1 → [0,4,1,3,2].
Each insert can take a little time because it shifts elements, so for n numbers the work is roughly n squared, but for these small inputs it is perfectly fine.