Question 6

Program to find second most frequent character

Program to find second most frequent character

Given a string, find the second most frequent character in it. Expected time complexity is O(n) where n is the length of the input string.

Examples:

Input: str = "aabababa";
Output: Second most frequent character is 'b'

Input: str = "abcd";
Output: No Second most frequent character

A simple solution is to start from the first character, count its occurrences, then second character and so on. While counting these occurrence keep track of max and second max. Time complexity of this solution is O(n2).
We can solve this problem in O(n) time using a count array with size equal to 256 (Assuming characters are stored in ASCII format). Following is C implementation of the approach. 

Program to find second most frequent character in a string

22 comments on “Question 6”


  • yadavvishal9464

    import java.util.*;

    public class SecondMostFrequentCharcter {
    static void secondFrequent(String s){
    HashMapmap=new HashMap();

    for(char ch:s.toCharArray()){
    map.put(ch,map.getOrDefault(ch,0)+1);
    }
    ArrayListal=new ArrayList(map.values());
    Collections.sort(al,Collections.reverseOrder());

    int first=al.get(0);
    int second =0;
    for(int freq:al){
    if(freq<first){
    second=freq;
    break;
    }
    }

    for(Map.Entryentry:map.entrySet()){
    if(second== entry.getValue()){
    System.out.println(“The second most frequent character in the string is:”+entry.getKey());
    break;
    }
    }

    }
    public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    String s=sc.next();
    secondFrequent(s);
    }
    }


  • jharianchal07

    python code
    from collections import Counter
    def SecondMostFrequent(nums):
    count=Counter(nums)
    frequent=count.most_common(2)[1][0]
    return frequent
    arr=[1,1,1,1,1,1,5,5,5,2,6,6,8,8]
    print(SecondMostFrequent(arr))


  • chibi.hariesh

    C++ solution class using MAP

    class Solution {
    public:
    string s;

    Solution(string str) : s(str) {}

    char mostFreqChar() {
    map cnt;
    int maxi = INT_MIN;
    char maxChar = ‘ ‘;

    for (char c : s) {
    cnt[c]++;
    if (cnt[c] > maxi) {
    maxi = cnt[c];
    maxChar = c;
    }
    }

    return maxChar;
    }
    };


  • guptaaastha825

    #include
    using namespace std;
    bool cmp(pair&a, pair&b){
    return a.second>b.second;
    }
    int main(){
    string s=”abcdd”;
    mapmp;
    for(int i=0;i<s.length();i++){
    mp[s[i]]++;
    }
    vector<pair>v;
    for(auto it:mp){
    v.push_back(it);
    }
    sort(v.begin(),v.end(),cmp);
    int val=v[0].second;
    for(int i=1;i<v.size();i++){
    if(v[i].second<val){
    cout<<v[i].first;
    break;
    }
    }
    }


  • vashukhanpara

    a=input()
    #making distinct data
    lis=”
    for i in a:
    if i not in lis:
    lis+=i
    # print(lis)

    #condition for all 1 values
    # if lis==a:
    # print(‘all have same 1’)

    l=[]
    for i in lis:
    cou=a.count(i)
    # print(cou,i)
    l=l+[[i]+[cou]]
    l.sort()
    # print(‘sorted list is ‘ , l)
    dicc= (dict(l))
    # print(dicc)
    val = list(dicc.values())
    val.sort()
    lval=val[-1]
    # print(val)

    #making condition of when we write max number 2
    e_val=[]
    for i in val:
    if i not in e_val:
    e_val+=[i]
    if len(e_val)==1:
    print(lis, ‘all are same times’)
    # print(lval)

    for j in range(lval):
    out=”
    for i in dicc:
    if dicc[i]==j:
    out+=str(i)
    if out==”:
    pass
    else:
    # print(val[-2])
    if j==e_val[-2]:
    print(out ,’–‘, j)


  • Bandaruanilkumar

    Anil#very simple python code
    str=input()
    l=list(str)
    v=[]
    for i in l:
    v.append(l.count(i))
    v=sorted(v)
    v=[*set(v)]
    for i in l:
    if l.count(i)==v[-2]:
    print(i)
    break


  • Harsha

    #simple python code
    n=input()
    d={}
    k=[]
    L=[]
    for i in n:
    k.append(i)
    for i in k:
    if i not in d:
    d[i]=1
    else:
    d[i]+=1
    for i in d.values():
    L.append(i)
    L.sort()
    A=L[-2]
    if max(L)==1:
    print(“No Second most frequent character”)
    else:
    for i,j in d.items():
    if j==A:
    print(i)


    • Varun Racha

      not all only 1
      #if max(L)==1:
      #print(“No Second most frequent character”)
      if all elements in l are same but not 1


  • Anonymous

    #include
    #include
    #include

    using namespace std;

    void checkPangram(string str){

    vector freq(26,0);
    int n=str.length();
    int val=0;

    transform(str.begin(),str.end(),str.begin(), ::tolower);

    for(int i=0;i<n;i++){
    freq[str[i]-97]+=1;
    }

    val=max_element(freq.begin(),freq.end())-freq.begin();
    freq[val]=0;
    // val=*max_element(freq.begin(),freq.end());
    val=max_element(freq.begin(),freq.end())-freq.begin();

    cout<<"Second most frequent: "<<char(val+97);
    };

    int main()
    {
    string str;
    getline(cin, str);

    checkPangram(str);

    return 0;
    }