LeetCode 27 — Remove Element Solution (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 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: ...
Road2Geeks
A Journey of Learning and Growth in the World of Technology