EasyTwo Pointers

Remove Element

Explanation & Solution

Description

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place and return the new length. The order of the elements may be changed. It does not matter what you leave beyond the new length.

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

Output: 2

Explanation: The function returns 2, with the first two elements of nums being [2, 2]. The value 3 has been removed.

Constraints

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

Approach

Two Pointers pattern

1. Initialize the Slow Pointer

  • Set k = 0 to track the write position for non-val elements
  • k will also represent the final length of the modified array

2. Scan Through the Array

  • Use a fast pointer i to iterate from 0 to nums.length - 1
  • Each element is checked exactly once

3. Keep Non-Matching Elements

  • If nums[i] !== val, the element should be kept
  • Copy nums[i] into nums[k] and increment k
  • This shifts all non-val elements to the front of the array

4. Skip Matching Elements

  • If nums[i] === val, do nothing
  • The fast pointer i advances, but k stays in place
  • This effectively overwrites val elements with the next valid one

5. Return the New Length

  • After the loop, k equals the number of elements that are not val
  • The first k elements of nums contain all the kept values

Key Insight

  • The two-pointer technique uses a slow pointer k (write position) and a fast pointer i (read position)
  • Every non-val element is written to the front, preserving them while discarding matches
Time
O(n)single pass through the array
Space
O(1)in-place modification, no extra storage

Visualization

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

Press ▶ or use ← → to step through

Pointer iPointer jProcessedDone
7 steps

Solution Code