Hide sidebar

Remove Element

Remove Element

Two Pointers
EasyLeetCode #27
10 min

Problem Statement

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Example

Example 1:

Input: nums = [3,2,2,3], val = 3

nums: [3, 2, 2, 3], val: 3

Output: 2, nums: [2,2,_,_]

Output: 2, nums = [2,2,_,_]

Solution

The two-pointer approach is efficient for this problem. We use one pointer (`k`) to keep track of the position of the next element that is not equal to `val`. We iterate through the array with another pointer (`i`), and if `nums[i]` is not equal to `val`, we place it at `nums[k]` and increment `k`.

Algorithm Steps

  • Initialize a pointer `k` to 0.
  • Iterate through the array with a pointer `i`.
  • If `nums[i]` is not equal to `val`, set `nums[k] = nums[i]` and increment `k`.
  • Return `k`.

Remove Element

Two Pointers Approach

Input: nums = [3, 2, 2, 3], val = 3

Output: 0, nums = [3, 2, 2, 3]

Progress1 / 1

Ready to start the visualization

Nums

3
2
2
3
Remove Element Solution

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