Lesson 18 of 50 intermediate

String Problems in Contests

Master the classic string patterns that show up in CP contests again and again!

Open interactive version (quiz + challenge)

Real-world analogy

String problems in CP are like word games and puzzles. Is 'racecar' the same forwards and backwards? (palindrome check!) Can you count the vowels in a sentence? (character counting!) Can you reverse a word? These are games you played in school — now you will solve them with code at lightning speed!

What is it?

String problems in competitive programming involve manipulating and analyzing text data. Common tasks include checking palindromes, reversing strings, counting character frequencies, finding anagrams, and extracting substrings. These are among the most popular problem types in beginner contests.

Real-world relevance

DNA sequences in biology are analyzed as strings of A, T, G, C — scientists check for palindromic sequences that are important for gene editing. Spell checkers look for anagrams and similar words. Search engines break text into substrings to find matches. String algorithms power the internet!

Key points

Code example

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    
    // 1. Check if palindrome
    string rev = s;
    reverse(rev.begin(), rev.end());
    if (s == rev) {
        cout << s << " is a palindrome!" << endl;
    } else {
        cout << s << " is NOT a palindrome." << endl;
    }
    
    // 2. Count vowels
    int vowels = 0;
    string vowelList = "aeiouAEIOU";
    for (char c : s) {
        if (vowelList.find(c) != string::npos) {
            vowels++;
        }
    }
    cout << "Vowels: " << vowels << endl;
    
    // 3. Frequency count
    int freq[26] = {0};
    for (char c : s) {
        if (isalpha(c)) {
            freq[tolower(c) - 'a']++;
        }
    }
    
    // Print most common letter
    int maxFreq = 0;
    char maxChar = 'a';
    for (int i = 0; i < 26; i++) {
        if (freq[i] > maxFreq) {
            maxFreq = freq[i];
            maxChar = 'a' + i;
        }
    }
    cout << "Most common letter: " << maxChar << " (" << maxFreq << " times)" << endl;
    
    return 0;
}
// Input:  racecar
// Output: racecar is a palindrome!
//         Vowels: 3
//         Most common letter: r (2 times)

Line-by-line walkthrough

  1. 1. We read a word into string s.
  2. 2. To check for palindrome: we make a copy, reverse it, and compare with the original.
  3. 3. reverse(s.begin(), s.end()) is a built-in function that reverses a string in place.
  4. 4. For counting vowels, we check if each character exists in our vowelList string.
  5. 5. string::npos means 'not found' — so if find() does NOT return npos, the character IS a vowel.
  6. 6. For frequency counting, we create an array of 26 zeros (one for each letter).
  7. 7. freq[tolower(c) - 'a']++ maps each letter to an index (a=0, b=1, ..., z=25) and counts it.
  8. 8. Finally, we scan the frequency array to find which letter appeared the most.

Spot the bug

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    
    // Check if palindrome
    bool isPalin = true;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] != s[s.length() - i]) {
            isPalin = false;
            break;
        }
    }
    
    if (isPalin) cout << "Palindrome!" << endl;
    else cout << "Not a palindrome." << endl;
    
    return 0;
}
// Input: racecar
// Expected: Palindrome!
// Actual: Might crash or give wrong answer
Need a hint?
When i is 0, what index does s.length() - i give you? Is that a valid index?
Show answer
The bug is s[s.length() - i]! When i=0, this accesses s[s.length()] which is out of bounds (valid indices are 0 to length-1). It should be s[s.length() - 1 - i]. Also, you only need to loop to s.length()/2 since you are comparing from both ends — checking the whole string compares each pair twice!

Explain like I'm 5

You know how 'racecar' spelled backward is still 'racecar'? That is a palindrome! It is like a word that looks the same in a mirror. And you know how 'listen' and 'silent' use the same letters, just mixed up? Those are anagrams — like scrambled words! String problems in coding contests are basically playing these word games, but your computer does the checking for you super fast!

Fun fact

The word 'palindrome' itself comes from the Greek words 'palin' (again) and 'dromos' (way/direction). The longest palindrome in English is debated, but 'tattarrattat' was coined by James Joyce in the novel Ulysses — it is the sound of a knock on the door! In CP, palindrome problems appear in at least 30% of beginner contests.

Hands-on challenge

Read a string and determine: (1) Is it a palindrome (ignoring case)? (2) Are there any duplicate characters? (3) What is the most frequent character? (4) Bonus: Read two strings and check if they are anagrams of each other!

More resources

Open interactive version (quiz + challenge) ← Back to course: CP Zero to Hero