← Back to Leo Academy Masterclass

Problem #27: Remove Element

Easy Array & String

Intuition & Strategy Breakdown

Use a write pointer starting at index 0. Iterate through the array; if the current element is not equal to val, write it at the write pointer and advance it.

Python 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

Java Solution

class Solution {
    public int removeElement(int[] nums, int val) {
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                nums[k++] = nums[i];
            }
        }
        return k;
    }
}
Watch Interactive Video on Leo Academy Main App