How to use Hashmap In Javascript
We will create a hash map to store the count of occurrences of elements from arr1. Now we Iterate through arr2, if an element is found in map, push it into the common array and decrement its count in map. Finally we iterate through arr3 and similarly push elements into finalCommon array if found in map and decrement their count. Return the finalCommon array
Example : To demonstrate finding common elements present in three sorted arrays using hashmap.
function findCommonElements(arr1, arr2, arr3) {
const map1 = {};
const map2 = {};
const map3 = {};
const common = [];
for (const num of arr1) {
map1[num] = (map1[num]
||
0
) + 1;
}
for (const num of arr2) {
map2[num] = (
map2[num]
||
0
) + 1;
}
for (const num of arr3) {
map3[num] = (
map3[num]
||
0
) + 1;
}
for (const num of arr1) {
if (
map1[num]
&&
map2[num]
&&
map3[num]
) {
common
.push(num);
map1[num]--;
map2[num]--;
map3[num]--;
}
}
return common;
}
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [4, 5, 6, 7, 8];
const arr3 = [1, 4, 5, 2, 6];
console
.log("common elements in three array is : ",
findCommonElements(arr1, arr2, arr3));
Output
common elements in three array is : [ 4, 5 ]
Time complexity : O(n + m + p)
Space complexity : O(min(n,m,p))
Find Common Elements In Three Sorted Arrays using JavaScript
JavaScript can be used to find the common elements in given three sorted arrays. We are given three different sorted arrays, we have to return common elements of three arrays.
Example:
Input
array1 = [1 , 2 , 3 , 4 ,5 ]
array2 = [3 , 4, 5 , 6 ,7 ]
array3 = [ 3 , 4 , 7 , 8 , 9]
Output
[3 , 4]
Below are different approaches to finding common elements present in three sorted arrays:
Table of Content
- Brute force Approach
- Using set
- Using Hashmap
Contact Us