Remove Element

Problem Id: 27 Difficulty: Easy Tag: Array Tag: Two Pointers


Intuition

We should have 2 pointers i and j. i for read and j for write. Since read is always before write, we don't need to consider where i == j.

Solution


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