Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gordjw/52c11099bf675b62bfef9aeb4e5d1f47 to your computer and use it in GitHub Desktop.
Save gordjw/52c11099bf675b62bfef9aeb4e5d1f47 to your computer and use it in GitHub Desktop.
Space efficient solution for Leetcode 80
"""
Basic solution
Time: O(nlogn)
- The main loop iterates through the original list (n + k) times
- The inner loop iterates through the tail of the list (k * log(n))
- In the worst case, k would be n/3, which means:
- main loop reduces to n + n/3 -> 4/3 * n -> n
- inner loop reduces to n/3 * log(n) -> log(n)
Space: O(n)
- We are editing in-place without creating any new lists or callables
"""
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
k = 0
i = 2
while i < len(nums) - k:
# As we find more triplicates, the final value in the list begins to duplicate
# E.g. ..., 3] -> ..., 3, 3] -> ..., 3, 3, 3] -> etc
# So we need to ignore the last k indices of the list when working out if we've finished
if nums[i] == nums[i-1] == nums[i-2]:
k += 1
for j in range(i+1, len(nums)):
nums[j-1] = nums[j]
i -= 1 # Recheck this index after we've shifted everything left
i += 1
return len(nums) - k
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment