JavaScript Program to Find Second Most Repeated Word in a Sequence
Last Updated :
29 Aug, 2024
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"
Approach 1: Using Map() 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.
JavaScript
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);
Time Complexity : O(Nlog(N))
Approach 2: Using Set() in JavaScript
Set() approach is to count the occurrences of each word in the array using a Map, then find the second most repeated word by comparing the occurrence counts. It iterates through the array to count word occurrences and efficiently identifies the second most repeated word using a Map data structure.
Syntax:
let occurrences = new Map();
occurrences.set()
Example: Below is the implementation of the above approach.
JavaScript
// Function to find the second most repeated word
function findSecondMostRepeatedWordInArray(words) {
// Store all the words with their occurrences
let occurrences = new Map();
for (let i = 0; i < words.length; i++) {
if (occurrences.has(words[i])) {
occurrences.set(words[i],
occurrences.get(words[i]) + 1);
} else {
occurrences.set(words[i], 1);
}
}
// Find the second largest occurrence
let firstMax =
Number.MIN_VALUE,
secondMax = Number.MIN_VALUE;
for (let [key, value] of occurrences) {
if (value > firstMax) {
secondMax = firstMax;
firstMax = value;
} else if (value > secondMax
&& value !== firstMax) {
secondMax = value;
}
}
// Return the word with
// an occurrence equal to secondMax
for (let [key, value] of occurrences) {
if (value === secondMax) {
return key;
}
}
}
// Driver program
let wordsArray = ["a", "b", "c", "a", "a", "b"];
console.log(findSecondMostRepeatedWordInArray(wordsArray));
Approach 3: Using Object.entries() and Reduce()
Using Object.entries() and reduce() to find the second most repeated word involves counting word frequencies with reduce(), converting the object into an array of entries, sorting it by frequency, and returning the second entry.
Example:
JavaScript
function findSecondMostRepeatedWord(sequence) {
const frequency = sequence.reduce((acc, word) => {
acc[word] = (acc[word] || 0) + 1;
return acc;
}, {});
const sorted = Object.entries(frequency).sort((a, b) => b[1] - a[1]);
return sorted[1] ? sorted[1][0] : null;
}
const sequence = ["apple", "banana", "banana", "apple", "cherry", "banana", "cherry"];
console.log(findSecondMostRepeatedWord(sequence)); // Output: "apple"
Approach 4: Using Sorting and Iteration
In this approach, we will first count the occurrences of each word using an object. Then, we will convert the object into an array of [word, count] pairs, sort this array by count in descending order, and finally, retrieve the second element from the sorted array to find the second most repeated word.
Example:
JavaScript
const findSecondMostRepeatedWord = (words) => {
const wordCounts = {};
words.forEach(word => {
wordCounts[word] = (wordCounts[word] || 0) + 1;
});
const wordCountPairs = Object.entries(wordCounts);
wordCountPairs.sort((a, b) => b[1] - a[1]);
return wordCountPairs[1] ? wordCountPairs[1][0] : null;
};
console.log(findSecondMostRepeatedWord(["1", "2", "1", "1", "2", "3"]));
console.log(findSecondMostRepeatedWord(["a", "b", "c", "a", "a", "b"]));
console.log(findSecondMostRepeatedWord(["apple", "banana", "apple", "orange", "banana", "banana"]));
console.log(findSecondMostRepeatedWord(["cat", "dog", "cat", "mouse", "dog", "dog", "cat"]));
Approach 5: Using Min-Heap (Priority Queue)
Use a priority queue to maintain the top two frequencies while iterating through the words. The heap data structure helps to keep track of the top elements efficiently.
Steps:
- Count Frequencies: Count the occurrences of each word using a hash map.
- Use Min-Heap: Maintain a min-heap to keep track of the top two frequencies. The heap ensures that you can easily access the smallest frequency among the top frequencies.
- Extract Second Most Frequent: After processing all words, the heap will contain the two highest frequencies. The second element in the heap represents the second most frequent word.
Example:
JavaScript
class PriorityQueue {
constructor() {
this.heap = [];
}
push(item) {
this.heap.push(item);
this.heap.sort((a, b) => a[1] - b[1]);
if (this.heap.length > 2) {
this.heap.shift(); // Keep only top 2 elements
}
}
top() {
return this.heap;
}
}
function findSecondMostRepeatedWord(words) {
const frequencyMap = new Map();
words.forEach(word => {
frequencyMap.set(word, (frequencyMap.get(word) || 0) + 1);
});
// Use priority queue to track top two frequencies
const pq = new PriorityQueue();
frequencyMap.forEach((count, word) => {
pq.push([word, count]);
});
const topTwo = pq.top();
return topTwo.length < 2 ? null : topTwo[0][0];
}
console.log(findSecondMostRepeatedWord(["1", "2", "1", "1", "2", "3"]));
console.log(findSecondMostRepeatedWord(["a", "b", "c", "a", "a", "b"]));
console.log(findSecondMostRepeatedWord(["apple", "banana", "apple", "orange", "banana", "banana"]));
console.log(findSecondMostRepeatedWord(["cat", "dog", "cat", "mouse", "dog", "dog", "cat"]));
Similar Reads
JavaScript Program to Find the First Repeated Word in String
Given a string, our task is to find the 1st repeated word in a string. Examples: Input: âRavi had been saying that he had been thereâOutput: hadInput: âRavi had been saying thatâOutput: No RepetitionBelow are the approaches to Finding the first repeated word in a string: Table of Content Using SetUs
4 min read
JavaScript Program to Find the Most Frequent Word in a String
We will explore a couple of approaches to finding the most frequent word in a string and provide clear explanations along with practical examples. Determining the most frequent word in a string is a common task in text analysis and processing. In JavaScript, we can accomplish this task using various
5 min read
JavaScript Program to Find Kâth Non-Repeating Character in String
The K'th non-repeating character in a string is found by iterating through the string length and counting how many times each character has appeared. When any character is found that appears only once and it is the K'th unique character encountered, it is returned as the result. This operation helps
6 min read
JavaScript Program for Printing Shortest Common Supersequence
A Shortest Common Supersequence (SCS) is the shortest or smallest string that contains two given strings as a subsequence. It is a minimal combination of characters that includes all elements of both input strings. In this article, we will see different approaches for printing the shortest common su
8 min read
JavaScript Program to Find Longest Common Substring Between Two Strings
In this article, we will see how to find the longest common substring between two strings in JavaScript. A substring is a contiguous sequence of characters within a string. It can be obtained by extracting part of the string starting from any position. We are going to write a JavaScript function tha
4 min read
JavaScript Program to Calculate the Frequency of Each Word in the Given String
Given a string, our task is to calculate the Frequency of Each Word in the Given String using JavaScript. Example:Input:"geeks for geeks is for geeks"Output:"geeks": 3 , "for": 2 , "is": 1 Below are the approaches for calculating the Frequency of Each Word in the Given String using JavaScript: Table
3 min read
JavaScript Count Distinct Occurrences as a Subsequence
Counting the distinct occurrences is the most common problem in string manipulation. Subsequences are the subsets of the characters in the string which appear in the same order but not necessarily in a consecutive manner. In the problem, the task is to find out the count of how many times a given su
6 min read
JavaScript Program Count number of Equal Pairs in a String
In this article, we are going to learn how can we count a number of equal pairs in a string. Counting equal pairs in a string involves finding and counting pairs of consecutive characters that are the same. This task can be useful in various applications, including pattern recognition and data analy
3 min read
JavaScript Program to find Lexicographically next String
In this article, we are going to learn how can we find the Lexicographically next string. Lexicographically next string refers to finding the string that follows a given string in a dictionary or alphabetical order.Examples: Input : testOutput : tesuExplanation : The last character 't' is changed to
3 min read
JavaScript Program to Print All Duplicate Characters in a String
In this article, we will learn how to print all duplicate characters in a string in JavaScript. Given a string S, the task is to print all the duplicate characters with their occurrences in the given string. Example: Input: S = âgeeksforgeeksâOutput:e, count = 4g, count = 2k, count = 2s, count = 2Ta
5 min read