File tree Expand file tree Collapse file tree 1 file changed +14
-11
lines changed
Sprint-1/Python/find_common_items Expand file tree Collapse file tree 1 file changed +14
-11
lines changed Original file line number Diff line number Diff line change 1- from typing import List , Sequence , TypeVar
1+ from typing import List , TypeVar
22
33ItemType = 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
611def 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 )
You can’t perform that action at this time.
0 commit comments