Remove Element
Given an integer array nums and an integer val, remove all occurrences of val in place . The order of the remaining elements may change. Return k, the number of elements that are not equal to val, after moving them to the front of nums. Use a slow pointer that marks the next write position, and a fast pointer that scans the array, copying over only the values that should be kept.
Constraints
- 0 ≤ nums.length ≤ 100
- 0 ≤ numsi ≤ 50
- 0 ≤ val ≤ 100
Example
nums = [3, 2, 2, 3], val = 32, nums = [2, 2, ...]Explanation The function returns k = 2, and the first two elements of nums are both 2.
In plain terms
- In place
- Making the change directly inside the given array instead of building a new one, using little to no extra memory.
Slow pointer writes kept values, fast pointer scans
slow=0, fast=0 (value 3), which equals val=3. Skip it, slow stays.
What happens in this step
slow = 0, fast = 0 (value 3) nums[fast] == val (3 == 3) Skip this element — do not write it, and slow does not move.
Steps to visualize
- Start slow at index 0.
- Advance fast through the array from the start.
- Whenever numsfast is not val, copy it into numsslow and move slow forward.
- Skip over any value equal to val without writing it.
- The final value of slow is the count of elements kept.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
slow=0, fast=0 (value 3), which equals val=3. Skip it, slow stays.
What happens in this step
slow = 0, fast = 0 (value 3) nums[fast] == val (3 == 3) Skip this element — do not write it, and slow does not move.
Solution
function removeElement(nums, val) {
let slow = 0;
for (let fast = 0; fast < nums.length; fast++) {
if (nums[fast] !== val) {
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [3, 2, 2, 3], val = 3 | 2 | example from the docstring |
nums = [], val = 5 | 0 | smallest valid input, an empty array |
nums = [2, 2, 2], val = 2 | 0 | every element equals val, nothing is kept |
nums = [1, 2, 3], val = 9 | 3 | val never appears, every element is kept |
nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2 | 5 | val scattered throughout a longer array |
nums = [7], val = 7 | 0 | single element that matches val |