cppAcademy
FROM LEARNING TO COMPETING

Intermediate.
Put your skills to the test.

Bulgarian Informatics Group D · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group D also includes challenging national-level problems. The six 2017 National tasks shared by Groups C and D use their existing permanent URLs. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP D2024 · EasyFrequency counting

Longest Equal-Letter Subsequence

National Olympiad — Municipal round (2024 season)

Submission name: maxsub.cpp

Problem summary

Select a longest subsequence consisting of one repeated lowercase letter. Ties favour the alphabetically earlier letter. Selected positions need not be consecutive.

Input

One lowercase word.

Output

The selected repeated-letter word.

Constraints

1≤word length≤200.

Worked example

Input and output for the worked example discussed below.

Input

bbabab

Output

bbbb

Solution analysis

  1. For one chosen letter, keep every occurrence. Gaps do not matter for a subsequence, so the best attainable length is its frequency rather than its longest contiguous run.
  2. Count all letters in 26 counters. Scan from a to z, replacing the best letter only when its count is strictly larger; equal counts preserve the earlier letter.
  3. For bbabab, a occurs twice and b four times, giving bbbb. In ayzyayzz, y and z both occur three times, so the tie rule selects yyy.

Why it works

All occurrences of a chosen letter form a valid subsequence, and no longer subsequence of that letter exists. Maximizing its count therefore maximizes the answer length; strict updates enforce the alphabetical tie-break.

Complexity: O(L+26) time and O(26) auxiliary space, excluding input and output.

Watch out. Do not confuse a subsequence with a contiguous substring. Updating on equal counts favours the wrong tied letter.

Commented C++17 solution

An independently written complete program with standard headers.

#include<array>
#include<iostream>
#include<string>
using namespace std;
int main(){
    string word;
    cin>>word;
    array<int,26>counts{};
    for(char letter:word){
        counts[letter-'a']++;
    }
    int best=0;
    for(int letter=1;letter<26;letter++){
        // Strict improvement preserves the earlier tied letter.
        if(counts[letter]>counts[best]){
            best=letter;
        }
    }
    cout<<string(counts[best],char('a'+best))<<'\n';
}

Source: Arena Olimpiici ↗