Skip to content

Commit de7ed1e

Browse files
committed
Refactor remove_duplicates function to improve time complexity and update documentation
1 parent 78e3cec commit de7ed1e

1 file changed

Lines changed: 17 additions & 18 deletions

File tree

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,24 @@
1-
from typing import List, Sequence, TypeVar
1+
def remove_duplicates(values):
22

3-
ItemType = TypeVar("ItemType")
4-
5-
6-
def remove_duplicates(values: Sequence[ItemType]) -> List[ItemType]:
7-
"""
8-
Remove duplicate values from a sequence, preserving the order of the first occurrence of each value.
9-
10-
Time complexity:
11-
Space complexity:
12-
Optimal time complexity:
13-
"""
143
unique_items = []
4+
seen = set()
155

166
for value in values:
17-
is_duplicate = False
18-
for existing in unique_items:
19-
if value == existing:
20-
is_duplicate = True
21-
break
22-
if not is_duplicate:
7+
if value not in seen:
238
unique_items.append(value)
9+
seen.add(value)
2410

2511
return unique_items
12+
13+
14+
print(remove_duplicates([1, 2, 2, 3, 1, 4]))
15+
# [1, 2, 3, 4]
16+
17+
"""
18+
Remove duplicate values from a sequence,
19+
preserving the order of the first occurrence.
20+
21+
Time complexity: O(n²)
22+
Space complexity: O(n)
23+
Optimal time complexity: O(n)
24+
"""

0 commit comments

Comments
 (0)