-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckSquare.js
More file actions
57 lines (48 loc) · 1.18 KB
/
checkSquare.js
File metadata and controls
57 lines (48 loc) · 1.18 KB
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
55
56
57
// checking Square in another array
// function isSquareCheck(array1, array2) {
// for (let i = 0; i < array1.length; i++) {
// let isSquare = false;
// for (let j = 0; j < array2.length; j++) {
// if (array1[i] * array1[i] === array2[j]) {
// isSquare = true;
// }
// if (j === array2.length - 1) {
// if (!isSquare) {
// return false;
// }
// }
// }
// }
// return true;
// }
// const result = isSquareCheck([1, 2, 3, 4], [1, 9, 4, 16]);
// console.log(result);
// time complexity O(n*2)
// optimized code
function checkSquare(array1, array2) {
let map1 = {};
let map2 = {};
for (item1 of array1) {
map1[item1] = (map1[item1] || 0) + 1;
}
console.log("Map1", map1);
for (item2 of array2) {
map2[item2] = (map2[item2] || 0) + 1;
}
console.log("Map2", map2);
for (let key in map1) {
console.log("key", key);
// obj key
if (!map2[key * key]) {
return false;
}
// vlaue compare
if (map1[key] !== map2[key * key]) {
return false;
}
}
return true;
}
const result = checkSquare([1, 2, 4, 2], [1, 4, 4, 16]);
console.log(result);
// time complexity O(n) linear