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.
#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.
How many mirrored comparisons are needed at most for lengths 6 and 5?
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.
#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
Mark complete when you can explain it yourself.