-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathremove_duplicates.py
More file actions
40 lines (31 loc) · 1.32 KB
/
remove_duplicates.py
File metadata and controls
40 lines (31 loc) · 1.32 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
from typing import List, Sequence, TypeVar
from collections import OrderedDict
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
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: O(n)
Space complexity: O(n)
Optimal time complexity: O(n)
"""
return list(OrderedDict.fromkeys(values))
# Used OrderedDict to create a dictionary with the list elements as keys (preserves order)
# Then, convert it back to a list to remove duplicates
# https://www.w3resource.com/python-exercises/list-advanced/python-list-advanced-exercise-8.php#:~:text=The%20Python%20OrderedDict.,order%20of%20the%20remaining%20elements.