Remove Element

Easy

Topics
ArrayTwo Pointers

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

30212233
keptequals 3, dropped
Order does not have to be preserved, which opens up the cheaper trick: instead of shifting everything down, a value to remove can be overwritten by the element at the end. Either way the answer is the surviving count, 2.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [3,2,2,3], target = 3
Output: 2

Example 2

0011222334054627
keptequals 2, dropped
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

  1. k = 0.
  2. For each value not equal to the target, write it at k and increment.
  3. 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 5

Order 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 k needs 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 k
SensAI
Beta
Tap the mic to stop voice mode