Remove Element In Place

Remove all occurrences of a value from an array in place using the slow/fast two pointer pattern, returning the new length in O(n).

Problem Statement

Given an array nums and a value val, remove all occurrences of val in place. Return the new length k; the first k elements should hold the values that are kept (order can change, extra space must be O(1)).

Example

Input:  nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Two elements remain (the 2s); the rest do not matter.

Two Pointer Approach

Use a slow write pointer and a fast read pointer moving in the same direction. The fast pointer scans every element; whenever it finds a value to keep, we copy it to the slow position and advance slow.

Complexity

  • Time: O(n)
  • Space: O(1)

Solution Code

Python

def removeElement(nums, val):
    slow = 0
    for fast in range(len(nums)):
        if nums[fast] != val:
            nums[slow] = nums[fast]
            slow += 1
    return slow

Java

int removeElement(int[] nums, int val) {
    int slow = 0;
    for (int fast = 0; fast < nums.length; fast++) {
        if (nums[fast] != val) nums[slow++] = nums[fast];
    }
    return slow;
}

C++

int removeElement(vector<int>& nums, int val) {
    int slow = 0;
    for (int fast = 0; fast < (int)nums.size(); fast++) {
        if (nums[fast] != val) nums[slow++] = nums[fast];
    }
    return slow;
}

Key Takeaways

  • Slow/fast pointers moving the same direction is the "read vs write" pattern.
  • The slow pointer always equals the count of kept elements.
  • Great template for Move Zeroes, Remove Duplicates, and similar in-place filters.
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.