Lesson 9 of 12

Mirror pairs and common beginnings

Check palindromes and shared prefixes without changing the text or crossing its boundaries.

A palindrome compares mirrored positions

A palindrome reads identically from both directions. Compare s[left] with s[n − 1 − left] for the first n / 2 positions. The middle of an odd-length string matches itself automatically. One mismatched pair proves the answer is no.

For level, compare l with l and e with e. For abca, the outside characters match but the inside pair b/c rejects it. The empty string has no mismatched pair and is accepted by this source task.

C++23
#include <iostream>
#include <string>

int main() {
    std::string s;
    std::getline(std::cin, s); // ASCII line of at most 100000 characters.
    int n = static_cast<int>(s.size());
    bool palindrome = true;
    for (int left = 0; left < n / 2; ++left) {
        int right = n - 1 - left;
        if (s[left] != s[right]) {
            palindrome = false;
            break;
        }
    }
    std::cout << (palindrome ? "YES" : "NO") << '\n';
    return 0;
}

Keep the problem’s exact comparison rule

This is an exact-character check. Level is not a palindrome because L differs from l. Spaces and punctuation count unless the problem explicitly says to ignore them. Preprocessing without permission changes the task.

Printing backward, reversing stored characters, and checking a palindrome are three different operations. A check needs only comparisons. If reversal is required, swap each mirrored pair once, just as for an array.

A common prefix stops at the first mismatch

A prefix begins at index zero. To find the longest common prefix of two strings, advance a length counter while it is within both lengths and the current characters match. A later match cannot repair an earlier mismatch in a prefix.

Put both bounds checks before the character access in the && condition. For training and trainers, the common prefix is train with length 5. Equal strings use their entire length; an empty input or immediate mismatch gives zero.

Pause & predict

How many mirrored comparisons are needed at most for lengths 6 and 5?

Choose an answer
Try it yourself

Turn the idea into code

Read two full ASCII lines, each at most 100000 characters and possibly empty. Print their longest common prefix length, then the prefix itself on the next line.

Give me a hint

Bounds first, equality second. Ordinary getline calls already consume each line ending.

Show the explained solution

The counter is the number of leading characters proven equal. Stop at a mismatch or either end. substr(0, length) then extracts exactly that common prefix.

C++23
#include <iostream>
#include <string>

int main() {
    std::string a, b;
    std::getline(std::cin, a);
    std::getline(std::cin, b);
    int n = static_cast<int>(a.size());
    int m = static_cast<int>(b.size());
    int length = 0;
    while (length < n && length < m && a[length] == b[length]) {
        ++length;
    }
    std::cout << length << '\n' << a.substr(0, length) << '\n';
    return 0;
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.