Create Target Array in the Given Order - Problem

Given two arrays of integers nums and index. Your task is to create target array under the following rules:

Rules:

  • Initially target array is empty.
  • From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
  • Repeat the previous step until there are no elements to read in nums and index.

Return the target array.

It is guaranteed that the insertion operations will be valid.

Input & Output

Example 1 — Basic Case
$ Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
💡 Note: Step by step: Insert 0 at index 0: [0]. Insert 1 at index 1: [0,1]. Insert 2 at index 2: [0,1,2]. Insert 3 at index 2: [0,1,3,2]. Insert 4 at index 1: [0,4,1,3,2].
Example 2 — Minimum Size
$ Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
Output: [0,1,2,3,4]
💡 Note: Start with [1], then [1,2], [1,2,3], [1,2,3,4], finally insert 0 at position 0: [0,1,2,3,4].
Example 3 — All at Beginning
$ Input: nums = [1], index = [0]
Output: [1]
💡 Note: Single element case: insert 1 at index 0 gives [1].

Constraints

  • 1 ≤ nums.length, index.length ≤ 100
  • nums.length == index.length
  • 0 ≤ nums[i] ≤ 100
  • 0 ≤ index[i] ≤ i

Visualization

Tap to expand
Create Target Array Problem OverviewInput: nums array01234Input: index array01221Sequential insertion processTarget array construction:[] → [0] → [0,1] → [0,1,2] → [0,1,3,2] → [0,4,1,3,2]Final Result:04132
Understanding the Visualization
1
Input Arrays
nums=[0,1,2,3,4] and index=[0,1,2,2,1] specify values and positions
2
Sequential Insertion
Insert each nums[i] at position index[i], shifting existing elements
3
Final Target
Result array [0,4,1,3,2] after all insertions
Key Takeaway
🎯 Key Insight: Simulate the insertion process using a dynamic list that handles element shifting automatically
Asked in
Apple 8 Microsoft 5
56.9K Views
Low Frequency
~10 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen