Home
DSA Patterns
Two Pointers
Remove Element
Remove Element
Remove every copy of a value from an array in place with a read pointer and a write pointer, and return how many values remain.
Problem Understanding
Remove Element: remove every occurrence of val from nums in place and return k, the number of elements left. The first k elements must hold the values that are not val; their order can change, and what comes after them does not matter.
Example: nums = [3, 2, 2, 3], val = 3 returns 2, with nums starting [2, 2, ...].
The Intuition: Copy the Keepers Forward
Think of building the answer at the front of the same array. Two pointers move left to right:
ireads every element.kis where the next kept value is written.
If nums[i] is not val, copy it to nums[k] and move k on; if it is val, just move past it. k never gets ahead of i, so a value is never overwritten before it has been read. It is the same read/write pattern as Remove Duplicates from Sorted Array, with a different rule for what to keep.
Interactive Walkthrough
The shaded prefix is what has been kept, nums[0..k). i reads ahead; a cell holding val is outlined red and skipped, and any other value is copied to k.
Dry Run Table
Input: nums = [3, 2, 2, 3], val = 3
| i | nums[i] | Action | k | Prefix |
|---|---|---|---|---|
| 0 | 3 | skip | 0 | [] |
| 1 | 2 | write at 0 | 1 | [2] |
| 2 | 2 | write at 1 | 2 | [2, 2] |
| 3 | 3 | skip | 2 | [2, 2] |
Return 2.
The Solution Template
Read with i, write every non-val value at k.
Remove Element Code
1var removeElement = function(nums, val) {2 let k = 0;3 for (let i = 0; i < nums.length; i++) {4 if (nums[i] !== val) nums[k++] = nums[i];5 }6 return k;7};
Edge Cases & Common Mistakes
- Every value is val: k stays 0.
- val not present: every value is written onto itself; k = n.
- Empty array: the loop never runs; return 0.
- Deleting with splice/erase in a loop: each removal shifts the rest, O(n²) and easy to get wrong with the index.
Summary
Build the answer at the front of the array: read every element with i, and copy each one that is not val to index k, moving k on. Return k. O(n) time, O(1) extra space.
More practice: DSA interview questions with answers · patterns cheat sheet
