Remove Element

Easy ArrayTwo Pointers

Problem

Given an integer array nums and a value val, remove all occurrences of val in place and return the new length. The order of the remaining elements may change.

Example 1 Input: nums = [3,2,2,3], val = 3 Output: 2 (nums = [2,2,_,_])
Example 2 Input: nums = [0,1,2,2,3,0,4,2], val=2 Output: 5 (nums = [0,1,4,0,3,_,_,_])

Constraints

Approach — Two Pointers

This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(1) extra space.

Solution code

Python

class Solution:
    def removeElement(self, nums, val):
        k = 0
        for x in nums:
            if x != val:
                nums[k] = x
                k += 1
        return k

Java

class Solution {
    public int removeElement(int[] nums, int val) {
        int w = 0;
        for (int n : nums) if (n != val) nums[w++] = n;
        return w;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Remove Element interactively → ← All solutions