573.Insert an Element at a Position
Easy
Given an array
nums, a position index and a value, return a new array with value inserted at index. Elements from that position onward move one place to the right. index may equal the length, meaning "add at the end".
Because an array's elements sit side by side in memory, making room in the middle means shiftingShifting ElementsMoving a run of elements one position along to open (or close) a gap. every later element. That makes insertion O(n) in the worst case, even when a built-in hides the loop — and it is why appending at the end is so much cheaper than inserting at the front.
Example 1:
Input: nums = [10,20,30], index = 1, value = 15
Output: [10,15,20,30]
Example 2:
Input: nums = [10,20,30], index = 3, value = 40
Output: [10,20,30,40]
+ 4 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ nums.length ≤ 1000 - ●
0 ≤ index ≤ nums.length - ●
-1000000 ≤ nums[i], value ≤ 1000000
nums =
[10, 20, 30]
index =
1
value =
15