Programming problem: Remove Element
Use a write pointer to overwrite matching values in place: iterate the array, and for each element not equal to `val`, write it at the pointer position and advance. Returns `k` non-matching elements in O(n) time and O(1) space.
Question
You are given an integer array nums and an integer val. Your task is to remove all occurrences of val from nums in-place.
After removing all occurrences of val, return the number of remaining elements, say k, such that the first k elements of nums do not contain val.
Note:
- The order of the elements which are not equal to
valdoes not matter. - It is not necessary to consider elements beyond the first
kpositions of the array. - To be accepted, the first
kelements ofnumsmust contain only elements not equal toval.
Return k as the final result.
Example 1
Input: nums = [1,1,2,3,4], val = 1
Output: [2,3,4]
Explanation: You should return k = 3 as we have 3 elements which are not equal to val = 1.
Example 2
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: [0,1,3,0,4]
Explanation: You should return k = 5 as we have 5 elements which are not equal to val = 2.
Constraints
0 <= nums.length <= 1000 <= nums[i] <= 500 <= val <= 100
Solution
function removeElement(nums: number[], val: number): number {
let k: number = 0;
for (const num of nums) {
if (num === val) continue;
nums[k] = num;
k++;
}
return k;
}