-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathremove_duplicates.py
More file actions
55 lines (38 loc) · 1.16 KB
/
remove_duplicates.py
File metadata and controls
55 lines (38 loc) · 1.16 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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:
Space complexity:
Optimal time complexity:
"""
unique_items = []
for value in values:
is_duplicate = False
for existing in unique_items:
if value == existing:
is_duplicate = True
break
if not is_duplicate:
unique_items.append(value)
return unique_items
"""
Time Complexity:
1 + 2 + 3 + ... + (n - 1) = n(n - 1)/2 = O(n²)
Space Complexity:
Even though we're just using .append(), the list grows linearly, so it is s O(n) space.
"""
#Optimal Solution
def remove_duplicates(values: Sequence[ItemType]) -> List[ItemType]:
seen = set()
unique_items = []
for value in values:
if value not in seen:
seen.add(value)
unique_items.append(value)
return unique_items
'''
Time Complexity: O(n)
Space Complexity: O(n) storing unique_items and seen
'''