Remove Element(#27)
Category: Array, Two Pointer
π§© Problem Statement
You are given an array nums and an integer val. Your task is to remove all occurrences of val from the array in-place, and return the number of elements that are not equal to val. The modified array should have all the remaining (non-val) elements at the beginning. The rest of the elements donβt matter. Return the count k, which is the number of elements not equal to val.
π Examples
Input: nums = [3,2,2,3], val = 3
Output: 2
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5
π§ Approach
Approach 1:
Two Pointer (Swap Based)
β’ Initialize two pointers `first = 0` and `sec = 0`.
β’ Loop while `sec < nums.length`.
β’ If `nums[sec] !== val`, swap `nums[first]` and `nums[sec]`, and increment `first`.
β’ Always increment `sec`.
Approach 2:
Cleaner Overwrite
β’ Initialize a pointer `k = 0`.
β’ Loop through each element in `nums`.
β’ If the element is not equal to `val`, overwrite `nums[k] = nums[i]`.
β’ Increment `k` after each overwrite.
π» Code
// Approach 1: Two Pointer (Swap Based)
var removeElement = function(nums, val) {
let first = 0;
let sec = 0;
while (sec < nums.length) {
if (nums[sec] !== val) {
[nums[first], nums[sec]] = [nums[sec], nums[first]];
first++;
}
sec++;
}
console.log(nums.slice(0, first));
return first;
};
console.log(removeElement([3,2,2,3], 3)); // Output: 2
console.log(removeElement([0,1,2,2,3,0,4,2], 2)); // Output: 5
// Approach 2: Cleaner Overwrite
var removeElement = function(nums, val) {
let k = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== val) {
nums[k] = nums[i];
k++;
}
}
console.log(nums.slice(0, k));
return k;
};
console.log(removeElement([3,2,2,3], 3)); // Output: 2
console.log(removeElement([0,1,2,2,3,0,4,2], 2)); // Output: 5
π Complexity
Time: O(n) β We iterate through the array once.
Space: O(1) β Done in-place without extra space.