Create Target Array In The Given Order
01 · Problem
You are given two integer arrays nums and index of the same length. Start with an empty array target. For each i from 0 to n - 1, in that order, insert nums[i] into target at position index[i], shifting any elements already at or after that position one place to the right.
Return target after all insertions. Every insertion is guaranteed to be valid, meaning index[i] is never larger than the current length of target.
02 · Examples
nums = [0,1,2,3,4], index = [0,1,2,2,1]
[0,4,1,3,2]
target evolves as [0] -> [0,1] -> [0,1,2] -> [0,1,3,2] -> [0,4,1,3,2].
nums = [5,6,7], index = [0,0,1]
[6,7,5]
Insert 5 at 0: [5]. Insert 6 at 0: [6,5]. Insert 7 at 1: [6,7,5].
nums = [1], index = [0]
[1]
A single insertion at position 0 gives [1].
03 · Constraints
- 011 <= nums.length == index.length <= 100
- 020 <= nums[i] <= 100
- 030 <= index[i] <= i
04 · Optimal complexity
- Time
- O(n^2)
- Space
- O(n)
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.