How to useMap() in JavaScript in Javascript
This approach involves iterating through the words in the sequence and using a hash map to count their frequencies. By maintaining two variables to track the most repeated and second most repeated words, we can efficiently identify the second most repeated word.
Syntax:
let frequencyMap = new Map();
frequency.sort()
Example: Below is the implementation of the above approach.
function findSecondMostFrequentElement(arr) {
let frequencyMap = new Map();
// Counting frequency of each element
for (let i = 0; i < arr.length; i++) {
if (frequencyMap.has(arr[i])) {
frequencyMap.set(arr[i],
frequencyMap.get(arr[i]) + 1);
} else {
frequencyMap.set(arr[i], 1);
}
}
let maxFrequency = Number.MIN_SAFE_INTEGER;
let frequencies = [];
// Finding the maximum frequency
for (let [key, value] of frequencyMap) {
if (value > maxFrequency) {
maxFrequency = value;
}
}
for (let [key, value] of frequencyMap) {
if (value !== maxFrequency) {
frequencies.push(value);
}
}
frequencies.sort((a, b) => a - b);
// Returning the second most frequent element
for (let [key, value] of frequencyMap) {
if (value ===
frequencies[frequencies.length - 1]) {
return key;
}
}
return "-1";
}
let arr = ["1", "2", "3", "1", "1", "2"];
let ans = findSecondMostFrequentElement(arr);
console.log(ans);
Output
2
Time Complexity : O(Nlog(N))
JavaScript Program to Find Second Most Repeated Word in a Sequence
Finding the second most repeated word in a sequence involves analyzing a given text or sequence of words to determine which word appears with the second-highest frequency. This task often arises in natural language processing and text analysis. To solve it, we need to parse the input sequence, count word frequencies, and identify the word with the second-highest count.
Examples:
Input : {"1", "2", "1", "1", "2", "3"}
Output : "2"
Input : {"a", "b", "c", "a", "a", "b"}
Output : "b"
Table of Content
- Approach 1: Using Map() in JavaScript
- Approach 2: Using Set() in JavaScript
- Approach 3: Using Object.entries() and Reduce()