Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Most Frequent Character in a String

Tech 1

Given a string, determine the character that appears most frequently. In case of ties, select the character with the smallest lexicographical order.

Approach 1: Nested Loop Counting

Use a structure to store each character and its frequency. For each character in the string, count its occurrences by scanning the remainder of the string. Sort the resulting array of structures by frequency (descending) and then by character (ascending).

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

struct CharInfo {
    char character;
    int frequency;
};

int main() {
    string input;
    cin >> input;
    
    vector<CharInfo> charList;
    for (int i = 0; i < input.size(); i++) {
        int count = 0;
        for (int j = i; j < input.size(); j++) {
            if (input[j] == input[i]) {
                count++;
            }
        }
        charList.push_back({input[i], count});
    }
    
    sort(charList.begin(), charList.end(), [](const CharInfo& a, const CharInfo& b) {
        if (a.frequency != b.frequency) {
            return a.frequency > b.frequency;
        }
        return a.character < b.character;
    });
    
    cout << charList[0].character << endl;
    cout << charList[0].frequency << endl;
    return 0;
}

Approach 2: Pair Array with Custom Comparator

Store pairs of frequency and character in an array. Count frequencies similarly to the first approach. Sort the array of pairs with a custom comparator that prioritizes higher frequnecy and then lower character.

#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
using namespace std;

int main() {
    string str;
    cin >> str;
    
    vector<pair<int, char>> freqPairs;
    for (int idx = 0; idx < str.size(); idx++) {
        int tally = 0;
        for (int j = idx; j < str.size(); j++) {
            if (str[j] == str[idx]) {
                tally++;
            }
        }
        freqPairs.push_back(make_pair(tally, str[idx]));
    }
    
    sort(freqPairs.begin(), freqPairs.end(), [](const pair<int, char>& a, const pair<int, char>& b) {
        if (a.first != b.first) {
            return a.first > b.first;
        }
        return a.second < b.second;
    });
    
    cout << freqPairs[0].second << endl;
    cout << freqPairs[0].first << endl;
    return 0;
}

Approach 3: Sorting and Linear Scan

Sort the string to group identical characters. Traverse the sorted string to count consecutive characters. Track the maximum frequency and the corresponding character, updating when a higher frequency is found. Handle the last group separately.

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {
    string text;
    cin >> text;
    
    sort(text.begin(), text.end());
    int maxFreq = 1;
    char maxChar = text[0];
    int currFreq = 1;
    
    for (int i = 1; i < text.size(); i++) {
        if (text[i] == text[i-1]) {
            currFreq++;
        } else {
            if (currFreq > maxFreq) {
                maxFreq = currFreq;
                maxChar = text[i-1];
            }
            currFreq = 1;
        }
    }
    
    // Check the last group
    if (currFreq > maxFreq) {
        maxFreq = currFreq;
        maxChar = text[text.size()-1];
    }
    
    cout << maxChar << endl;
    cout << maxFreq << endl;
    return 0;
}
Tags: string

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.