Remove element

October 8, 2022

array-and-hashmap

Problem URL: Remove element

We will take a pointer at the beginning of the array, then iterate over the whole array. If the value doesn't match the given values, we assing it to the pointer's position of the array and then forward it position. Finally return the pointer position as result.

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

Time Complexity: O(n)
Space Complexity: O(1)