File tree Expand file tree Collapse file tree
JavaScript/findCommonItems Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11/**
22 * Finds common items between two arrays.
33 *
4- * Time Complexity:
5- * Space Complexity:
6- * Optimal Time Complexity:
4+ * Time Complexity: O(n * m) - filter iterates firstArray, includes iterates secondArray
5+ * Space Complexity: O(n) - Set and result array
6+ * Optimal Time Complexity: O(n + m) - convert secondArray to Set for O(1) lookups
77 *
88 * @param {Array } firstArray - First array to compare
99 * @param {Array } secondArray - Second array to compare
1010 * @returns {Array } Array containing unique common items
1111 */
12- export const findCommonItems = ( firstArray , secondArray ) => [
13- ...new Set ( firstArray . filter ( ( item ) => secondArray . includes ( item ) ) ) ,
14- ] ;
12+ export const findCommonItems = ( firstArray , secondArray ) => {
13+ const secondSet = new Set ( secondArray ) ;
14+ const seen = new Set ( ) ;
15+ const result = [ ] ;
16+
17+ for ( const item of firstArray ) {
18+ if ( secondSet . has ( item ) && ! seen . has ( item ) ) {
19+ seen . add ( item ) ;
20+ result . push ( item ) ;
21+ }
22+ }
23+
24+ return result ;
25+ } ;
Original file line number Diff line number Diff line change @@ -9,13 +9,17 @@ 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) - nested loops compare every pair
13+ Space Complexity: O(n) - stores common items in list
14+ Optimal time complexity: O(n + m) - convert second_sequence to set for O(1) lookups
1515 """
16+ second_set = set (second_sequence )
17+ seen = set ()
1618 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 )
19+
20+ for item in first_sequence :
21+ if item in second_set and item not in seen :
22+ seen .add (item )
23+ common_items .append (item )
24+
2125 return common_items
You can’t perform that action at this time.
0 commit comments