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 in the Given Order INPUT nums array: 0 1 2 3 4 index array: 0 1 2 2 1 Index: 0 1 2 3 4 Process pairs: (0,0) (1,1) (2,2) (3,2) (4,1) Insert nums[i] at index[i] in target array ALGORITHM STEPS 1 Insert 0 at idx 0 target: [0] 2 Insert 1 at idx 1 target: [0,1] 3 Insert 2 at idx 2 target: [0,1,2] 4 Insert 3 at idx 2 target: [0,1,3,2] (shifts 2 right) 5 Insert 4 at idx 1 target: [0,4,1,3,2] (shifts 1,3,2 right) Insert Operation: list.insert(index[i], nums[i]) FINAL RESULT Target Array: 0 4 1 3 2 0 1 2 3 4 Output: [0, 4, 1, 3, 2] OK - Complete! Insertion Trace: [] --> [0] [0] --> [0,1] [0,1] --> [0,1,2] [0,1,2] --> [0,1,3,2] [0,1,3,2] --> [0,4,1,3,2] Key Insight: The optimal approach uses the built-in list insert() method. For each i from 0 to n-1, insert nums[i] at position index[i]. The insert operation automatically shifts existing elements to the right. Time: O(n^2) due to shifts | Space: O(n) for the result array TutorialsPoint - Create Target Array in the Given Order | Optimal Solution
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