Official

B - Frequency Editorial by evima


Let’s restate the problem.

  • Among the characters that appear most frequently in the string \(S\), print the one that comes earliest in alphabetical order.

Approach 1. For loop

Implement the following process.

  1. Declare some data structure \(a\) to hold the count of each character from a to z, and initialize the count for all characters to \(0\).
  2. For each character \(c\) in \(S\), do the following:
    • Add \(1\) to \(a_c\).
  3. Declare a variable \(\mathrm{ans}\) and assign a to it.
  4. For each character \(c\) from b to z (in this order), do the following:
    • If \(a_c\) is greater than \(a_\mathrm{ans}\), assign \(c\) to \(\mathrm{ans}\).
  5. Print the value of \(\mathrm{ans}\).

You can use the following for “some data structure”:

  • Associative arrays (such as C++’s map or unordered_map, Python’s dict, etc.)
  • Regular arrays (treating a, \(\dots\), z as ASCII values \(97, \dots, 122\))

Below is a sample implementation in C++ (assuming the character encoding is ASCII, a safe assumption in competitive programming).

#include <iostream>
using namespace std;

int main() {
    string S;
    cin >> S;
    int a[128] = {};
    for (char c: S) {
        ++a[c];
    }
    char ans = 'a';
    for (char c = 'b'; c <= 'z'; ++c) {
        if (a[c] > a[ans]) {
            ans = c;
        }
    }
    cout << ans << endl;
}

Approach 2. Library

Some languages have library functions that count the occurrences of characters in a string, which can replace the first for loop in Approach 1. Below is a sample implementation using Python’s count function.

S = input()
ans = 'a'
for i in range(ord('b'), ord('z') + 1):
    c = chr(i)
    if S.count(c) > S.count(ans):
        ans = c
print(ans)

(It iterates over \(S\) multiple times, but it’s not a problem because it’s short.)

Library functions can also replace the second for loop in Approach 1. However, be careful that the tiebreaker is alphabetical order (for example, the tiebreaker for Python’s Counter.most_common is the order of first appearance, so it is unfortunately insufficient by itself). Below is a sample implementation using Python’s Counter class and max function.

from collections import Counter

S = input()
print(max(Counter(S).items(), key=lambda x: (x[1], -ord(x[0])))[0])

posted:
last update: