80. Remove Duplicates from Sorted Array II (Medium)

 Remove Duplicates from Sorted Array II is a Medium level problem.


Given an array of integers sorted in non-decreasing (aka, increasing) order, remove all but TWO of each duplicate value IN PLACE and return the number of unique values in the list.

My solution to this was an adaptation to 26. Remove Duplicates From Sorted Array. It was relatively quick an easy to update indices to solve this.

Challenges were off-by-one bugs with my indexes. This solution would have benefited from some white-boarding.

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 means we found some number of dupes
# If end - beg == 1 then we found exactly two dupes, so we keep them both.
# We only proceed to remove elements if there are more than two dupes.
if beg != end and end - beg != 1:
# Truncate nums by removing all the dupes, leaving just
# the first two occurences of val
nums[beg+2:] = nums[end+1:]

dupeCount += end-beg-1
# Shift the end pointer
end = beg - 1
beg = end

return origCount - dupeCount

Runtime: 48 ms. Beats 78.73% of users.
Memory: 16.64 MB. Beats 22.43% of users.

So just okay performance on runtime, but pretty weak performance on memory.

It is nice to have solved my first Medium using a solution from an Easy.

Comments

Popular posts from this blog

846. Hand of Straights (medium)

409. Longest Palindrome (Easy)