Peeush Agarwal > Engineer. Learner. Builder.

I am a Machine Learning Engineer passionate about creating practical AI solutions using Machine Learning, NLP, Computer Vision, and Azure technologies. This space is where I document my projects, experiments, and insights as I grow in the world of data science.

View on GitHub

Intuition

To remove all occurrences of a value from an array in-place, we can minimize the number of writes by swapping unwanted elements with the last element. This way, we avoid shifting elements multiple times and only move each element at most once.

Approach

We use two pointers:

While i < j:

At the end, i is the count of elements not equal to val.

Complexity

Code

from typing import List

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        i = 0
        j = len(nums)
        # Loop until i reaches j
        while i < j:
            if nums[i] == val:
                # Swap with the last unchecked element
                nums[i] = nums[j - 1]
                j -= 1
            else:
                i += 1
        # i is the new length of the array without val
        return i

Back to Problem Statement