27 - Remove Element
Wednesday, 16 September 2026
The write pointer pattern with a keep-condition, plus the swap-from-the-end variant that the relaxed ordering requirement allows.
Problem
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val to be k. To get accepted,
you need to do the following things:
- Change the array
numssuch that the firstkelements ofnumscontain the elements which are not equal toval. The remaining elements ofnumsare not important, as well as the size ofnums. - Return
k.
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_] Constraints:
0 <= nums.length <= 1000 <= nums[i] <= 500 <= val <= 100
Approach
The same write pointer as 26. Remove Duplicates and 283. Move Zeroes, with the keep-condition swapped out again. Those three
problems are one algorithm: idx counts what has been kept and marks the next slot to write, i reads ahead, and everything satisfying the condition gets compacted to the front.
Write Pointer
Keep whatever isn’t val.
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
const int n = nums.size();
int idx = 0;
for (int i = 0; i < n; i++) {
if (nums[i] != val) {
nums[idx] = nums[i];
idx++;
}
}
return idx;
}
}; nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2
i=0 0 keep -> idx=1
i=1 1 keep -> idx=2
i=2 2 drop
i=3 2 drop
i=4 3 keep -> nums[2]=3, idx=3
i=5 0 keep -> nums[3]=0, idx=4
i=6 4 keep -> nums[4]=4, idx=5
i=7 2 drop
return 5, prefix [0, 1, 3, 0, 4] - time:
O(n)— one pass - space:
O(1)— one index