SDE & MLE Prep

27. Remove Element

Problem

Remove every occurrence of val from nums in place and return the number k of remaining values; the first k slots must hold them in any order.

Example: nums = [0,1,2,2,3,0,4,2], val = 2 → 5, first five slots 0,1,3,0,4 in any order

Copy every element not equal to val to the write pointer k.

Complexity: O(n).

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        k = 0
        for x in nums:
            if x != val:
                nums[k] = x
                k += 1
        return k