-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathremove_duplicates.py
More file actions
35 lines (22 loc) · 783 Bytes
/
remove_duplicates.py
File metadata and controls
35 lines (22 loc) · 783 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from typing import List, Sequence, TypeVar
ItemType = TypeVar("ItemType")
def remove_duplicates(values: Sequence[ItemType]) -> List[ItemType]:
"""
Remove duplicate values from a sequence, preserving the order of the first occurrence of each value.
Time complexity:
ANSWER: O(n)
Because the sequence is looped through once.
Space complexity:
ANSWER: O(n)
Because a set is used to track seen value
Optimal time complexity:
ANSWER: O(n)
Each value is processed once using a set for faster lookup
"""
unique_items = []
seen = set()
for value in values:
if value not in seen:
seen.add(value)
unique_items.append(value)
return unique_items