Last active
February 6, 2024 22:24
-
-
Save gordjw/52c11099bf675b62bfef9aeb4e5d1f47 to your computer and use it in GitHub Desktop.
Space efficient solution for Leetcode 80
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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