Skip to main content

Solution: LeetCode 27 — Remove Element

LeetCode 27 — Remove Element

Solution 1 (Optimal)

This version is in-place, single-pass, O(n) time and O(1) space. It preserves the relative order of kept elements.


class Solution:
  def removeElement(self, nums: List[int], val: int) -> int:
    p = 0
    for i in nums:
      if i != val:
        nums[p] = i
        p += 1
    return p

Solution 2(Optimal)

This version is in-place, single-pass, O(n) time and O(1) space. It preserves the relative order of kept elements.

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        l, r = 0, len(nums) - 1
        while l <= r:
            if nums[l] == val:
                nums[l] = nums[r]
                r -= 1
            else:
                l += 1
        return l
return l

Common Mistakes

  • Modifying the list while iterating with for x in nums plus remove or pop — this changes indices and skips elements.
  • Returning the modified list instead of the new length.
  • Trying to maintain order with an algorithm designed to minimize writes (e.g., two-pointer-swap) without noting that order won’t be preserved.
  • Using extra memory (creating a new list) when interview expects in-place solution.

Edge Cases

  • Empty array: nums = [] → return 0.
  • All elements equal to val: return 0.
  • No elements equal to val: return original length.
  • Mix of occurrences: both forward-write and two-pointer-swap handle these; forward-write preserves order.

Quick Comparison

Version In-place Space Order preserved When to use
Forward writes Yes O(1) Yes Default — preserves order, simple
Two-pointer swap Yes O(1) No When you want fewer writes and don't care about order

posted by Rohit Singh

Comments