LeetCode 26 — Remove Duplicates from Sorted Array
1)approach 1 (Using extra list — not optimal)
Works correctly but uses extra space and has O(n²) behavior because if i not in uniques is an O(n) check for each element.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
uniques = []
for i in nums:
if i not in uniques:
uniques.append(i)
k = len(uniques)
for i in range(k):
nums[i] = uniques[i]
return k
Complexity: Time O(n²), Space O(n). Not in-place as required by the problem.
2) Optimal two-pointer solution (Front write — O(n), O(1) space)
This is the recommended in-place approach for a sorted array: keep a write pointer p that marks the last unique position.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
p = 0
for i in range(1, len(nums)):
if nums[i] != nums[p]:
p += 1
nums[p] = nums[i]
return p + 1
Why it works: array is sorted so duplicates are consecutive; copying forward never overwrites needed future values. Complexity: Time O(n), Space O(1).
3) LeetCode top answer (Enumerate-based variant — same logic)
The top answer you found is the same algorithm expressed slightly differently: it uses enumerate and compares the current element to nums[loc]. Semantically identical to the two-pointer write approach.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
loc = 0
for i, e in enumerate(nums):
if e != nums[loc]:
loc += 1
nums[loc] = e
return loc + 1
Notes: All three implementations produce the same result. The differences are style — the enumerate variant starts from the first element and maintains loc as the position of the last unique element. Performance is O(n) and O(1) space for the two-pointer / enumerate variants.
Comments
Post a Comment
Share your views on this blog😍😍