Skip to content

Commit bd26423

Browse files
committed
Refactor find_common_items
1 parent 3e425da commit bd26423

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed
Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,24 @@
1-
from typing import List, Sequence, TypeVar
1+
from typing import List, TypeVar
22

33
ItemType = TypeVar("ItemType")
44

5+
# Original version: O(n × m) due to nested loops
6+
# Refactored version: O(n + m) using a set for constant-time lookups
7+
# This is optimal and cannot be further reduced because all input
8+
# elements must be processed at least once.
9+
# use this link :https://www.w3schools.com/python/ref_set_intersection.asp
510

611
def find_common_items(
7-
first_sequence: Sequence[ItemType], second_sequence: Sequence[ItemType]
12+
first_sequence, second_sequence
813
) -> List[ItemType]:
914
"""
1015
Find common items between two arrays.
1116
12-
Time Complexity:
13-
Space Complexity:
14-
Optimal time complexity:
17+
Time Complexity:O(n + m)
18+
Space Complexity:O(n + m)
19+
Optimal time complexity:O(n + m)
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+
second_set=set(second_sequence)
22+
first_set=set(first_sequence)
23+
common_set=first_set.intersection(second_set)
24+
return list(common_set)

0 commit comments

Comments
 (0)