๐Ÿง‘โ€๐Ÿ’ป How I Solved "Remove Element" on LeetCode and Improved My Approach

๐Ÿง‘โ€๐Ÿ’ป How I Solved "Remove Element" on LeetCode and Improved My Approach

By Devang Shaurya Pratap Singh SinghLeet Code
Advertisement

Problem Link: Remove Element - LeetCode


๐Ÿ“Œ Problem Statement

We are given an array nums and a value val. We need to remove all instances of val in-place and return the number of elements left after removal. The first k elements of nums should contain the elements that are not equal to val.

โžก Key Points:

  • Must do it in-place (no extra arrays).

  • Return the new length k (number of elements that are not val).

  • Time complexity should be O(n) and space O(1).


๐ŸŽฏ My Initial Approach

Here’s the code I initially wrote:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i = 0 # loop counter
        rp = 0 # replace pointer
        total = 0 # number of non-matching elements

        while i < len(nums):
            if nums[i] != val:
                total += 1
                nums[rp] = nums[i]
                rp += 1
                i += 1
            else:
                i += 1
        return total

๐Ÿ” Analysis of My Approach

  • Used two pointers:

    • i to loop through the array

    • rp to place non-val elements in the front

  • Maintained a separate total counter for non-val elements.

โœ… Correct but slightly verbose – maintaining both rp and total is redundant since rp itself indicates the count.


๐Ÿ”‘ Optimizing My Solution

After studying editorial solutions and this YouTube explanation (credits to niits), I realized I could simplify my approach significantly.

Here’s the cleaner, optimal version:

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        k = 0  # write pointer

        for i in range(len(nums)):
            if nums[i] != val:
                nums[k] = nums[i]
                k += 1

        return k

๐Ÿ› ๏ธ Step-by-Step Algorithm

  1. Initialize k = 0 – This is the write pointer and also the count of valid elements.

  2. Loop through each element in nums.

    • If nums[i] != val, overwrite nums[k] with nums[i] and increment k.

    • If nums[i] == val, skip it.

  3. Return k, which is the count of non-val elements.


โœ… Complexity Analysis

  • Time Complexity: O(n) – We iterate through the array once.

  • Space Complexity: O(1) – We modify the array in place.


๐Ÿ”— References & Credits


๐Ÿš€ Key Learning

  • My original code worked but was overly verbose.

  • The optimized solution uses a single pointer (k) to both track position and count, making it cleaner and more Pythonic.

  • Always revisit editorials and community solutions to simplify your approach.

Advertisement
2025 GyanAangan.in All rights reserved.