find the second most repeated string in a sequence

 Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence.


Note: No two strings are the second most repeated, there will be always a single string.



Example 1:

Input:

N = 6

arr[] = {aaa, bbb, ccc, bbb, aaa, aaa}

Output: bbb

Explanation: "bbb" is the second most 

occurring string with frequency 2.


Example 2:

Input: 

N = 6

arr[] = {geek, for, geek, for, geek, aaa}

Output: for

Explanation: "for" is the second most

occurring string with frequency 2.


method :

  1. Store all the words in a map with their occurrence with word as key and its occurrence as value.
  2. Find the second largest value in the map and return the string with second largest value

c++ implementation:

string secFrequent (string a[], int n)
    {  
        
        map<string,int>m;
        for(int i=0;i<n;i++)
        m[a[i]]++;
        
        int max1=INT_MIN;
        int max2=INT_MIN;
        string s;
        
        for(auto i:m){
           max1=max(max1,i.second);
        }
        
        for(auto i:m)
        {
           if(i.second!=max1)
           {
               max2=max(max2,i.second);
               if(max2==i.second)
               s =i.first;
           }
        }
        
        return s;
    }
Time Complexity: O(n)  ,where n is the length of the string



darkmode