๐งโ๐ป How I Solved "Remove Element" on LeetCode and Improved My Approach
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 notval
). -
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
-
Initialize
k = 0
– This is the write pointer and also the count of valid elements. -
Loop through each element in
nums
.-
If
nums[i] != val
, overwritenums[k]
withnums[i]
and incrementk
. -
If
nums[i] == val
, skip it.
-
-
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
-
Problem: Remove Element - LeetCode
-
Video Explanation (by niits): Watch on YouTube
๐ 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.