Remove Element [Easy] — Read/Write Two Pointers
Advertisement
Problem Statement
Remove all occurrences of val from array in-place. Return the number of elements not equal to val. The relative order of other elements may change.
Input: nums=[3,2,2,3], val=3 → Output: 2, nums=[2,2,_,_]
Intuition
Read pointer scans entire array; write pointer only advances when the current element should be kept. After the scan, write pointer = new length.
Solutions
C
int removeElement(int* nums, int n, int val) {
int w=0;
for (int r=0;r<n;r++) if(nums[r]!=val) nums[w++]=nums[r];
return w;
}
C++
int removeElement(vector<int>& nums, int val) {
int w=0;
for (int x:nums) if(x!=val) nums[w++]=x;
return w;
}
Java
public int removeElement(int[] nums, int val) {
int w=0;
for (int x:nums) if(x!=val) nums[w++]=x;
return w;
}
JavaScript
var removeElement = function(nums, val) {
let w=0;
for (const x of nums) if(x!==val) nums[w++]=x;
return w;
};
Python
def removeElement(nums: list[int], val: int) -> int:
w = 0
for x in nums:
if x != val:
nums[w] = x
w += 1
return w
Complexity
- Time: O(n)
- Space: O(1)
Advertisement