-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathfind_common_items.py
More file actions
23 lines (17 loc) · 870 Bytes
/
find_common_items.py
File metadata and controls
23 lines (17 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from typing import List, Sequence, TypeVar
ItemType = TypeVar("ItemType")
def find_common_items(
first_sequence: Sequence[ItemType], second_sequence: Sequence[ItemType]
) -> List[ItemType]:
"""
Find common items between two arrays.
Time Complexity: O(n * m * k) in the worst case, where:
- n = length of first_sequence (outer loop)
- m = length of second_sequence (inner loop)
- k = length of common_items, because "i not in common_items" requires scanning this list
Space Complexity:In first implementation We only store the common items in a new list.--> O(n)
Optimal time complexity:This can be improved to O(n + m) by using a set for faster lookups.
"""
first_set=set(first_sequence) # O(n)
commons=[item for item in second_sequence if item in first_set] # O(m)
return list(set(commons)) # remove duplicates