Remove Element

Two Pointer

Problem

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

For example:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3]
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]

Thought Process

  • We'll use two pointer approach: one pointer to iterate through the array and the other pointer to keep track of the position of the elements that aren't key. We will start from index 0.

Solution

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

Last updated