Remove Element

Remove all occurrences of val from an array in place; return the new length.

Easy
Time O(n) Space O(1)
LeetCode
2 min read
two-pointers array

Problem#

Given an integer array nums and an integer val, remove all occurrences of val in place. Return the new length k; the first k elements of nums must hold the surviving values.

Examples#

  • nums = [3,2,2,3], val = 3k = 2, nums = [2,2,_,_]
  • nums = [0,1,2,2,3,0,4,2], val = 2k = 5, nums = [0,1,3,0,4,_,_,_]

Constraints#

  • 0 <= nums.length <= 100.

Approach#

Write-pointer w lags behind the read-pointer i. Copy nums[i] into nums[w] whenever it’s not the target value, incrementing w. Return w.

Solution#

Remove Element
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int w = 0;
for (int x : nums) {
if (x != val) nums[w++] = x;
}
return w;
}
};

Editorial#

The write-pointer pattern handles all in-place filtering: copy when the predicate holds, otherwise drop. No swapping needed because the order of survivors is preserved and we only ever read positions ≥ w.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.