Remove Element
Remove all occurrences of val from an array in place; return the new length.
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 = 3→k = 2,nums = [2,2,_,_]nums = [0,1,2,2,3,0,4,2], val = 2→k = 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#
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; }};func removeElement(nums []int, val int) int { w := 0 for _, x := range nums { if x != val { nums[w] = x w++ } } return w}from typing import List
class Solution: def removeElement(self, nums: List[int], val: int) -> int: w = 0 for x in nums: if x != val: nums[w] = x w += 1 return wfunction removeElement(nums, val) { let w = 0; for (const x of nums) { if (x !== val) nums[w++] = x; } return w;}class Solution { public int removeElement(int[] nums, int val) { int w = 0; for (int x : nums) { if (x != val) nums[w++] = x; } return w; }}function removeElement(nums: number[], val: number): number { let w = 0; for (const x of 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#
Related#