-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathfindCommonItems.js
More file actions
32 lines (30 loc) · 882 Bytes
/
findCommonItems.js
File metadata and controls
32 lines (30 loc) · 882 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Finds common items between two arrays.
*
* Time Complexity: Logarythmic? No Quadratic
*
// nested so includes loops over each item in first arr
// nested loops are not efficient and used filter and inlcudes
//array.inlcudes method goes item by item
* Space Complexity: O(N)
* Optimal Time Complexity: o(N)?
*
* @param {Array} firstArray - First array to compare
* @param {Array} secondArray - Second array to compare
* @returns {Array} Array containing unique common items
*/
export const findCommonItems = (firstArray, secondArray) => {
// ...new Set(firstArray.filter((item) => secondArray.includes(item))),
const dictToCheck = {};
const common = [];
for (const item of firstArray) {
dictToCheck[item] = true;
}
for (const item of secondArray) {
if (dictToCheck[item]) {
common.push(item);
dictToCheck[item] = false;
}
}
return common;
};