Skip to content

Commit 31c81a3

Browse files
committed
Refactor: optimize to O(n) using set while preserving order
1 parent d56406c commit 31c81a3

1 file changed

Lines changed: 14 additions & 9 deletions

File tree

Sprint-1/Python/remove_duplicates/remove_duplicates.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,24 @@ 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: O(n)
11+
The old code checked the list repeatedly, which is O(n^2).
12+
I used a 'Set' to remember seen items for O(1) lookups, while appending to a list to keep the order.
13+
14+
Space Complexity: O(n) - We use a Set to store seen items and a List for the result.
15+
16+
Optimal time complexity: O(n) - We must iterate through the input at least once.
1317
"""
18+
19+
# Refactor: I used a Set to track items we have seen because checking a Set is O(1).
20+
# I also used a List to build the result so we keep the original order.
21+
seen = set()
1422
unique_items = []
1523

1624
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:
25+
# Check if we have seen this value before.
26+
if value not in seen:
2327
unique_items.append(value)
28+
seen.add(value)
2429

2530
return unique_items

0 commit comments

Comments
 (0)