Remove Element Algorithm
Given an array and a target value, remove every occurrence of that value in-place. Return how many elements remain.
27 Mar 2024

Given an array and a target value, remove every occurrence of that value in-place. Return how many elements remain.
Order doesn't matter. Only the first k slots count.
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,,]
The intuition
Think of it like packing a suitcase. Walk through each item. If it's not the thing you want to remove, toss it into the "keep" pile. A write pointer tracks where that pile ends.
var removeElement = function(nums, val) {
let writeIndex = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== val) {
nums[writeIndex] = nums[i];
writeIndex++;
}
}
return writeIndex;
};
Complexity
- Time: O(n) — single pass.
- Space: O(1) — no extra allocation.
When to use this
This is the simplest form of the two-pointer "partition" pattern. You'll see it everywhere: filtering arrays, compacting data, partitioning around a pivot in quicksort.
The cost of in-place: you lose the original array. If the caller needs it later, you've got a bug. Always know who owns the data.