Second most repeated word in a sequence in C++

In this tutorial, we are going to learn about the program for the Second most repeated word in a sequence in C++. Firstly we have an introduction to the problem and secondly, after that, we find a solution and method for it. Finally, write the code in c++.

Introduction

A sequence of strings is a collection of strings which we have entered by the user. In this problem, we have to find the second most repeated word in a sequence.

We are going to use maps in this solution. Maps will save the values of the word and their occurrences. Word will be used as the key and occurrence will be used as value.

Algorithm to solve this problem is :

  1. Create a map. Save words as keys and occurrences as values.
  2. Find the second most value.
  3. Again traverse the map and find the key with the second-most value and return it.

C++ Program to find second most repeated word in a sequence

#include <bits/stdc++.h> 
using namespace std; 

string repeat(vector<string> seq) 
{ 
  
    unordered_map<string, int> occ; 
    for (int i = 0; i < seq.size(); i++) 
        occ[seq[i]]++; 

    int first_max = INT_MIN, sec_max = INT_MIN; 
    for (auto it = occ.begin(); it != occ.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; 
    } 

    for (auto it = occ.begin(); it != occ.end(); it++) 
        if (it->second == sec_max) 
            return it->first; 
} 

int main() 
{
    string str;
    int n;
    vector<string> seq ;
    cout<<"Enter the number of string : ";
    cin>>n;
    cout<<"Enter the strings : ";
    for(int i=0;i<n;i++){
    	cin>>str;
    	seq.push_back(str);
  }
    cout <<"The second most used word is : "<< repeat(seq); 
    return 0; 
}

Input and Output:

Enter the number of string : 4
Enter the strings : yogi yogi odd yogi
The second most used word is : odd

Code above Firstly takes a sequence of strings and secondly enter the values inside the map. Finally, the second largest value is extract from the map. Function repeat is called with the sequence as the parameter

Also Checkout :

Insert data from text file into an array in C++

Leave a Reply

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