|
U
Pro27. Insert Element at Index in Array
Easy
Problem Description
Given an array of N integers, insert a value val at a specified 0-based index idx (0≤idx≤N) by shifting subsequent elements to the right.
Input Format
- •Line 1: An integer N (0≤N≤105).
- •Line 2: N space-separated integers A0,…,AN−1. (Omitted if N=0).
- •Line 3: Two space-separated integers idx and val.
Output Format
Print the N+1 space-separated integers of the updated array.
Example 1:
Input:
4 1 2 4 5 2 3
Output:
1 2 3 4 5
Explanation: Insert 3 at index 2 shifts 4 and 5 to the right.
Example 2:
Input:
3 10 20 30 0 5
Output:
5 10 20 30
Explanation: Insert 5 at head (index 0).
Example 3:
Input:
0 0 99
Output:
99
Explanation: Insert 99 into an empty array.
Constraints:
Standard integer bounds: 32-bit signed integer or input range [1, 10^5].Time complexity target: O(N) or O(N log N) where applicable.Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online
Code
|Loading Code Editor...
SavedLn 1, Col 1
param_1 =
param_2 =
param_3 =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit