File tree Expand file tree Collapse file tree
Sprint-1/Python/find_common_items Expand file tree Collapse file tree Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments