26. Remove Duplicates from Sorted Array (Easy)
Remove Duplicates from Sorted Array is an Easy level problem.
Given an array of integers sorted in non-decreasing (aka, increasing) order, remove all the duplicate values IN PLACE and return the number of unique values in the list.
My first solution to this was:
class Solution:
def removeDuplicates(self, nums: list[int]) -> int:
dupeCount = 0
origLength = len(nums)
i = 0
while (i < len(nums) - 1):
thisElem = nums[i]
nextElem = nums[i+1]
while thisElem == nextElem:
dupeCount += 1
if (i<len(nums)-2):
nums[i+1:] = nums[i+2:]
else:
nums[i+1:] = []
if i+1 < len(nums):
nextElem = nums[i+1]
else:
nextElem = None
i += 1
return origLength - dupeCount
That solution worked, but it was super slow, beating only 5.07% of users in Runtime and 23.85% of users in Memory use.
My original solution was complicated and messy. I wrote it, start to finish, without really considering the problem. My first implementation was buggy and missed easy edge cases (like walking off the start of the array, for example).
I re-evaluated the problem and white boarded up the skeleton of a solution.
Thinking through the problem really helped with solving it. My second solution had a mistake in the shifting of the end index, at first, but once I fixed that it ran great. This solution beat 98.86% of users in Runtime and 57.6% of users in memory use.
class Solution: def removeDuplicates(self, nums: list[int]) -> int: end = len(nums)-1 beg = end dupeCount = 0 origCount = len(nums)
while (end > 0): val = nums[end] lookBack = val
while (beg > 0 and lookBack == val): lookBack = nums[beg-1] if lookBack == val: beg -= 1 # beg is now the index of the first occurence of val if beg != end: # Truncate nums by removing all the dupes, leaving just # the first occurence of val nums[beg+1:] = nums[end+1:] dupeCount += end-beg # Shift the end pointer end = beg - 1 beg = end
Comments
Post a Comment