Skip to content

Commit 0ebc392

Browse files
author
Fatma Degirmenci
committed
Refactor find_common_items using a Set for faster lookups
1 parent 41316b6 commit 0ebc392

1 file changed

Lines changed: 11 additions & 9 deletions

File tree

Sprint-1/Python/find_common_items/find_common_items.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,16 @@ def find_common_items(
88
) -> List[ItemType]:
99
"""
1010
Find common items between two arrays.
11+
Time Complexity: O(n * m * k) in the worst case, where:
12+
- n = length of first_sequence (outer loop)
13+
- m = length of second_sequence (inner loop)
14+
- k = length of common_items, because "i not in common_items" requires scanning this list
1115
12-
Time Complexity:
13-
Space Complexity:
14-
Optimal time complexity:
16+
Space Complexity:In first implementation We only store the common items in a new list.--> O(n)
17+
18+
19+
Optimal time complexity:This can be improved to O(n + m) by using a set for faster lookups.
1520
"""
16-
common_items: List[ItemType] = []
17-
for i in first_sequence:
18-
for j in second_sequence:
19-
if i == j and i not in common_items:
20-
common_items.append(i)
21-
return common_items
21+
first_set=set(first_sequence) # O(n)
22+
commons=[item for item in second_sequence if item in first_set] # O(m)
23+
return list(set(commons)) # remove duplicates

0 commit comments

Comments
 (0)