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 @@ -9,13 +9,22 @@ def find_common_items(
99 """
1010 Find common items between two arrays.
1111
12- Time Complexity:
13- Space Complexity:
14- Optimal time complexity:
12+ Time Complexity: O(n * m)
13+ Space Complexity: O(n)
14+ Optimal time complexity: O(n + m)
15+ Explanation: The function uses a nested loop to check every possible pair of items in the two
16+ sequences to see if they are common.
17+ This results in a time complexity of O(n * m).
18+ Using a set for constant-time lookups can reduce the time complexity to O(n + m)
19+ by first converting one of the sequences into a set and then checking for common items in a single loop.
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+ lookup = set (second_sequence )
22+ result = []
23+ seen = set ()
24+
25+ for item in first_sequence :
26+ if item in lookup and item not in seen :
27+ seen .add (item )
28+ result .append (item )
29+
30+ return result
You can’t perform that action at this time.
0 commit comments