|
U
Pro29. Delete Element in O(1) Without Preserving Order
Easy
Problem Description
Given an array of N integers and an index idx, delete the element at index idx in O(1) time by overwriting it with the last element of the array and shrinking the size by 1.
Input Format
- •Line 1: An integer N (1≤N≤105).
- •Line 2: N space-separated integers A0,…,AN−1.
- •Line 3: An integer idx (0≤idx<N).
Output Format
Print the N−1 space-separated integers, or EMPTY if N=1.
Example 1:
Input:
5 10 20 30 40 50 1
Output:
10 50 30 40
Explanation: Element 20 at index 1 is replaced by last element 50.
Example 2:
Input:
1 7 0
Output:
EMPTY
Explanation: Removing the single element leaves EMPTY.
Example 3:
Input:
4 1 2 3 4 3
Output:
1 2 3
Explanation: Deleting the last element directly yields 1 2 3.
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