Skip to content

Commit 70b2396

Browse files
author
Fatma Degirmenci
committed
Refactor remove_duplicates to use a set for O(n) removal of duplicates
1 parent 4d26911 commit 70b2396

1 file changed

Lines changed: 8 additions & 13 deletions

File tree

Sprint-1/Python/remove_duplicates/remove_duplicates.py

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,14 @@ def remove_duplicates(values: Sequence[ItemType]) -> List[ItemType]:
77
"""
88
Remove duplicate values from a sequence, preserving the order of the first occurrence of each value.
99
10-
Time complexity:
11-
Space complexity:
12-
Optimal time complexity:
10+
Time complexity: Outer loop O(n) Inner loop (worst case) O(n) total --->O(n*n)
11+
Space complexity: We have an array ,unique_items, total --->O(n)
12+
Optimal time complexity: O(n) using a set for fast lookups
1313
"""
1414
unique_items = []
15-
16-
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:
23-
unique_items.append(value)
24-
15+
seen = set()
16+
for value in values: # O(n)
17+
if value not in seen: # O(1)
18+
seen.add(value) # O(1)
19+
unique_items.append(value) # O(1)
2520
return unique_items

0 commit comments

Comments
 (0)