-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmostFrequentElements.js
More file actions
35 lines (32 loc) · 960 Bytes
/
Copy pathmostFrequentElements.js
File metadata and controls
35 lines (32 loc) · 960 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
33
34
35
/*
This code demonstrates how to efficiently find the most
frequent element of an array.
Let n be the size of the array.
Time complexity: O(n)
Space complexity: O(n)
*/
function computeElementsFrequencies(arr, map) {
// Computer the number of occurrences of each
// array element.
for (const element of arr) {
if (map.has(element)) {
map.set(element, map.get(element) + 1);
} else {
map.set(element, 1);
}
}
}
function findMostFrequentElements(map) {
const maxFrequency = Math.max.apply(null, Array.from(map.values()));
// Return an array containing the most frequent elements
return Array.from(map.keys()).filter((key) => {
return map.get(key) === maxFrequency;
});
}
const map = new Map();
computeElementsFrequencies(
["Wissam", "Wissam", "Chadi", "Chadi", "Fawzi"],
map
);
const mostFrequentElements = findMostFrequentElements(map);
console.log(mostFrequentElements); // [ 'Wissam', 'Chadi' ]