U

27. Insert Element at Index in Array

Easy

Problem Description

Given an array of NN integers, insert a value valval at a specified 0-based index idxidx (0≤idx≤N0 \le idx \le N) by shifting subsequent elements to the right.

Input Format

  • •Line 1: An integer NN (0≤N≤1050 \le N \le 10^5).
  • •Line 2: NN space-separated integers A0,…,AN−1A_0, \dots, A_{N-1}. (Omitted if N=0N = 0).
  • •Line 3: Two space-separated integers idxidx and valval.

Output Format

Print the N+1N+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