Remove Element
Easy
Topics
Given an array nums and a value target, remove all occurrences of target in-place and return the number of remaining elements k.
Example 1
Input: nums = [3,2,2,3], target = 3 Output: 2
Example 2
Input: nums = [0,1,2,2,3,0,4,2], target = 2 Output: 5
Constraints
- 0 <= nums.length <= 100
- 0 <= nums[i], target <= 50
Editorial — intuition, approach, complexity and pitfalls
Intuition
Same in-place compaction pattern as removing sorted duplicates, with a simpler predicate: keep everything that is not the target. One write index, one scan.
Because the write index trails the read index, the write can never destroy an unread value.
Approach
k = 0.- For each value not equal to the target, write it at
kand increment. - Return
k.
Dry Run
nums = [0,1,2,2,3,0,4,2], val = 2
0 keep -> k=1 [0,...]
1 keep -> k=2 [0,1,...]
2 skip
2 skip
3 keep -> k=3 [0,1,3,...]
0 keep -> k=4 [0,1,3,0,...]
4 keep -> k=5 [0,1,3,0,4,...]
2 skip
return 5Order among the kept elements is preserved here. The problem permits any order, which allows an alternative: swap the last element into the current slot and shrink the array. That does fewer writes when matches are rare, and is the better answer if the question says writes are expensive.
Complexity
- Time — O(n): one pass.
- Space — O(1): one index.
Common Pitfalls
- Returning the filtered array rather than the count.
- Removing elements from the list while iterating it, which skips elements and is quadratic.
- In the swap-from-the-end variant, advancing the read index after a swap. The value just pulled in has not been examined yet, so the index must stay put.
- Assuming the tail beyond
kneeds blanking.
Full Solution — all languages
class Solution:
def removeElement(self, nums, target):
k = 0
for x in nums:
if x != target:
nums[k] = x
k += 1
return kimport java.util.*;
class Solution {
public int removeElement(int[] nums, int target) {
int k = 0;
for (int x : nums) {
if (x != target) {
nums[k] = x;
k++;
}
}
return k;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int removeElement(vector<int>& nums, int target) {
int k = 0;
for (int x : nums) {
if (x != target) {
nums[k] = x;
k++;
}
}
return k;
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var removeElement = function(nums, target) {
let k = 0;
for (const x of nums) {
if (x !== target) {
nums[k] = x;
k++;
}
}
return k;
};