Strings: Second most repeated word in a sequence

Problem Statement:

You are given a strings, your task is to find the second most repeated string in the given sequence.

Example

Input : {“aaa”, “bbb”, “ccc”, “bbb”, “aaa”, “aaa”}
Output : bbb

Solution

The solution is very simple.

Store all the words in a map and the count of the times that word is repeated.

Now we get the second largest value in Map.

Solution in C++

#include <vector>    
#include <algorithm>  
//visit www.ProDeveloperTutorial.com for 450+ solved questions  
#include <iostream>    
#include <string>
#include <unordered_map>

using namespace std;

string get_sec_most_repeated_word(vector<string> seq) 
{ 
  
    unordered_map<string, int> word_with_count; 
    for (int i = 0; i < seq.size(); i++) 
        word_with_count[seq[i]]++; 
  
    // find the second largest occurrence 
    int first_max = INT_MIN;
    int sec_max = INT_MIN; 

    for (auto it = word_with_count.begin(); it != word_with_count.end(); it++) 
    { 
        if (it->second > first_max) 
        { 
            sec_max = first_max; 
            first_max = it->second; 
        } 
  
        else if (it->second > sec_max &&  
                 it->second != first_max) 
            sec_max = it->second; 
    } 
  
    // return the second max
    for (auto it = word_with_count.begin(); it != word_with_count.end(); it++) 
        if (it->second == sec_max) 
            return it->first; 
} 
  
int main() 
{ 
    vector<string> seq = { "bbb", "aaa", "bbb", "ddd", "aaa", "aaa" }; 
    cout << "The second most repeated word in a sequence = "<<get_sec_most_repeated_word(seq); 
    return 0; 
} 

Output:

The second most repeated word in a sequence = bbb

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *