Skip to content

Commit 74477db

Browse files
committed
80. Remove Duplicates from Sorted Array II
- Language: Python. - Time complexity: O(n+n). - Space complexity: O(1).
1 parent e96ff79 commit 74477db

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

python_solutions/lc_80_remove_duplicates_from_sorted_array_2/__init__.py

Whitespace-only changes.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def removeDuplicates(self, nums: list[int]) -> int:
3+
# Time complexity: O(n + n). Space complexity: O(1).
4+
i, j = 0, 1
5+
cnt = 1
6+
counter = 0
7+
# first pass through the array
8+
# marking as empty value
9+
while i < len(nums) or j < len(nums):
10+
while j < len(nums) and nums[i] == nums[j]:
11+
cnt += 1
12+
if cnt > 2:
13+
nums[j] = None
14+
counter += 1
15+
j += 1
16+
i = j
17+
j += 1
18+
cnt = 1
19+
j = 1
20+
# second pass through the array
21+
# moving empty values
22+
for i in range(len(nums)):
23+
if nums[i] is not None:
24+
j += 1
25+
continue
26+
while j < len(nums) and nums[j] is None:
27+
j += 1
28+
if j < len(nums):
29+
nums[i], nums[j] = nums[j], nums[i]
30+
return len(nums) - counter
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import pytest
2+
3+
from lc_80_remove_duplicates_from_sorted_array_2.lc_80 import Solution
4+
5+
test_cases = (
6+
# preset cases
7+
([1, 1, 1, 2, 2, 3], 5, [1, 1, 2, 2, 3, None]),
8+
([0, 0, 1, 1, 1, 1, 2, 3, 3], 7, [0, 0, 1, 1, 2, 3, 3, None, None]),
9+
# common cases
10+
([-1, -1, -1, -1, 0, 0, 0, 3, 3, 4], 7, [-1, -1, 0, 0, 3, 3, 4, None, None, None]),
11+
(
12+
[-1, -1, -1, -1, 0, 0, 0, 3, 3, 4, 4, 4, 4],
13+
8,
14+
[-1, -1, 0, 0, 3, 3, 4, 4, None, None, None, None, None],
15+
),
16+
([-1, 2, 2, 2, 2, 5], 4, [-1, 2, 2, 5, None, None]),
17+
([-1, -1, -1, -1, -1], 2, [-1, -1, None, None, None]),
18+
([-1, -1, 0, 0, 3, 3], 6, [-1, -1, 0, 0, 3, 3]),
19+
# corner cases
20+
([-15], 1, [-15]),
21+
([-15, -15], 2, [-15, -15]),
22+
([0, 0, 0], 2, [0, 0, None]),
23+
([-15, 0, 1, 4], 4, [-15, 0, 1, 4]),
24+
)
25+
26+
27+
@pytest.mark.parametrize(("nums", "ans", "deduplicated_nums"), test_cases)
28+
def test_success_v0(
29+
nums: list[int],
30+
ans: int,
31+
deduplicated_nums: list[int],
32+
solution: Solution,
33+
):
34+
assert solution.removeDuplicates(nums) == ans
35+
assert nums == deduplicated_nums
36+
37+
38+
@pytest.fixture
39+
def solution() -> Solution:
40+
return Solution()

0 commit comments

Comments
 (0)