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
Java Program to Find the Most Repeated Word in a Text File Map and Map.Entry interface will be used as the Map interface maps unique keys to values. A key is an object that is used to retrieve a value at a later date. The Map.Entry interface enables you to work with a map entry. Also, we will use the HashMap class to store items in "key/valueâ pairs and acc
3 min read
Javascript Program To Find Length Of The Longest Substring Without Repeating Characters Given a string str, find the length of the longest substring without repeating characters. For âABDEFGABEFâ, the longest substring are âBDEFGAâ and "DEFGAB", with length 6.For âBBBBâ the longest substring is âBâ, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
5 min read
Java Program to Find Occurrence of a Word Using Regex Java's regular expressions, or regex, let you do advanced text manipulation and matching. Regex offers a handy approach for searching for a term in a text wherever it appears. In this article, we will learn to find every occurrence of a word using regex. Program to Find Occurrence of a Word Using Re
2 min read
Java Program to Search a Particular Word in a String Using Regex In Java string manipulation, searching for specific words is a fundamental task. Regular expressions (regex) offer a powerful and flexible approach to achieve this search. It matches the patterns simply by comparing substrings. In this article, we will learn how to search for a particular word in a
3 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching Given a set of strings, find the longest common prefix. Examples:Input : {âgeeksforgeeksâ, âgeeksâ, âgeekâ, âgeezerâ}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- âgeeksforgeeksâ and âgeeksâ. What is the longest common prefix in
3 min read
Java Program to Find Duplicate Words in a Regular Expression Given an Expression which is represented by String. The task is to find duplicate elements in a Regular Expression in Java. Use a map or set data structures for identifying the uniqueness of words in a sentence. Examples: Input : str = " Hi, I am Hritik and I am a programmer. " Output: I am Explanat
3 min read
C# Program to Estimate the Frequency of the Word âisâ in a Sentence Given a string as input, we need to write a program in C# to count the frequency of the word "is" in the string. The task of the program is to count the number of the occurrence of the given word "is" in the string and print the number of occurrences of "is". Examples: Input : string = "The most sim
2 min read