Skip to content

Commit f7a266e

Browse files
committed
80. Remove Duplicates from Sorted Array II
- Language: Python. - Time complexity: O(n). - Space complexity: O(1). - Solution: https://algo.monster/liteproblems/80
1 parent 74477db commit f7a266e

File tree

1 file changed

+18
-0
lines changed
  • python_solutions/lc_80_remove_duplicates_from_sorted_array_2

1 file changed

+18
-0
lines changed

python_solutions/lc_80_remove_duplicates_from_sorted_array_2/lc_80.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,21 @@ def removeDuplicates(self, nums: list[int]) -> int:
2828
if j < len(nums):
2929
nums[i], nums[j] = nums[j], nums[i]
3030
return len(nums) - counter
31+
32+
def removeDuplicatesV1(self, nums: list[int]) -> int:
33+
# Time complexity: O(n). Space complexity: O(1).
34+
# Solution: https://algo.monster/liteproblems/80
35+
# Pointer to track the position for the next valid element
36+
write_index = 0
37+
# Iterate through each element in the array
38+
for current_num in nums:
39+
# Allow element if:
40+
# 1. We have less than 2 elements (write_index < 2), OR
41+
# 2. Current element is different from the element 2 positions back
42+
if write_index < 2 or current_num != nums[write_index - 2]:
43+
# Place the current element at the write position
44+
nums[write_index] = current_num
45+
# Move write pointer forward
46+
write_index += 1
47+
# Return the length of the modified array
48+
return write_index

0 commit comments

Comments
 (0)