-
Notifications
You must be signed in to change notification settings - Fork 0
/
containsCommonItems.js
54 lines (49 loc) · 1.32 KB
/
containsCommonItems.js
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Given 2 arrays, create a function that let's a user know (true/false) whether these two arrays contain any common items
//For Example:
// const array1 = ['a', 'b', 'c', 'x'];
// const array2 = ['z', 'y', 'i'];
//should return false.
//-----------
const array1 = ['a', 'b', 'c', 'x'];
const array2 = ['z', 'y', 'x'];
//should return true.
// 2 parameters - arrays - no size limit
// return true or false
function commonOne(arr1, arr2) {
for(let i = 0; i < arr1.length; i++) {
for(let j = 0; j < arr2.length; j++) {
if(arr1[i] === arr2[j]) {
return true;
}
}
}
return false;
}
//O(a*b)
//O(1) - Space Complexity
function commonTwo(arr1, arr2) {
// loop through first array and create object where properties === items in array
let map = {}
for(let i = 0; i < arr1.length; i++) {
if(!map[arr1[i]]) {
const item = arr1[i]
map[item] = true
}
}
// loop through secdon array and check if item in second array exists on created object
for(let j = 0; j < arr2.length; j++) {
if(map[arr2[j]]) {
return true;
}
}
return false
}
//O(a + b) Time Complexity
//O(a) Space Complexity
//Language specific solution
function commonThree(arr1, arr2) {
return arr1.some(item => arr2.includes(item))
}
commonOne(array1, array2)
commonTwo(array1, array2)
commonThree(array1, array2)