C++ 0214.cpp
class Solution {
public:
string shortestPalindrome(string s) {
auto r = s;
reverse(r.begin(), r.end());
for (int skip = 0; skip < r.size(); skip++)
{
int length = s.size() - skip;
// check last
if (r[length - 1 + skip] != s[length - 1])
continue;
bool ok = true;
int steps[] = { 111, 50, 7, 1 };
for (auto offset : steps)
{
if (offset > length)
continue;
for (int i = 0; i < length; i += offset)
{
if (r[i + skip] != s[i])
{
ok = false;
break;
}
}
if (!ok)
break;
}
// found it
if (ok)
{
while (skip-- > 0)
r += r[skip];
return r;
}
}
return "";
}
};
Difficulty
and has an acceptance rate of about 43% (800k+ submissions).
Typical patterns to solve this problem:
- Hash Function
- Rolling Hash
- String
- String Matching
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation builds the shortest palindrome that can be obtained by adding characters in front of the given string s. It first creates a reversed copy of s, then searches for the longest prefix of s that is also a suffix of the reversed string. When such a prefix is found, the missing characters are appended to the reversed copy, producing the desired palindrome.
Core Steps
The algorithm proceeds through a sequence of distinct operations.
Create a reversed copy
auto r = s;
reverse(r.begin(), r.end());
A separate string r holds the characters of s in reverse order. This enables direct index-based comparison between the original and its mirror image without recomputing the reverse repeatedly.
Iterate over possible skip values
for (int skip = 0; skip < r.size(); skip++)
{
int length = s.size() - skip;
// ...
}
The variable skip represents how many characters from the front of r are ignored when aligning it with s. For each skip, length denotes the candidate palindrome prefix length that must match.
Quick mismatch test
if (r[length - 1 + skip] != s[length - 1])
continue;
Before performing a full scan, the code checks the last character of the candidate segment. A mismatch here discards the current skip immediately, saving work for non-matching positions.
Sampled verification with multiple strides
bool ok = true;
int steps[] = { 111, 50, 7, 1 };
for (auto offset : steps)
{
if (offset > length)
continue;
for (int i = 0; i < length; i += offset)
{
if (r[i + skip] != s[i])
{
ok = false;
break;
}
}
if (!ok)
break;
}
The steps array defines a set of stride lengths. The outer loop iterates over these strides, starting with the largest. For each stride that does not exceed length, the inner loop compares characters at positions spaced by the stride. If any mismatch appears, the verification aborts early. The final stride of 1 guarantees a complete check when the larger strides have not found a discrepancy.
Append the missing prefix and return
if (ok)
{
while (skip-- > 0)
r += r[skip];
return r;
}
When a matching prefix is identified (ok remains true), the algorithm appends the characters that were skipped, taken from the front of r in reverse order. This constructs the shortest palindrome and returns it immediately.
Fallback return
return "";
If no matching configuration is found after exhausting all skip values, an empty string is returned. In practice, the loop always finds a solution because the trivial case of adding the entire reversed string is always valid.
Edge Cases Handled
When the input string is empty, the reversed copy is also empty, the outer loop does not execute, and the function returns an empty string, which is a correct palindrome.
A single-character string passes the quick mismatch test because the last character comparison succeeds, and the sampled verification confirms the match. The while loop that appends skipped characters does not execute because skip is zero, so the original character is returned unchanged.
If the entire string is already a palindrome, the first iteration (skip == 0) satisfies all checks. The while loop again skips appending, and the function returns the original string unchanged.
When all characters are identical, the quick mismatch test always succeeds, and the sampled verification quickly validates the match because every stride encounters identical characters. The algorithm therefore terminates after the first iteration.
Performance Optimizations
The code avoids recomputing the reversed string by storing it once in r.
The early mismatch test eliminates many candidate skip values without entering the more expensive nested loops.
The use of a decreasing stride array (111, 50, 7, 1) provides a coarse-to-fine verification strategy. Larger strides quickly detect mismatches in long strings, reducing the number of character comparisons needed before falling back to a full linear scan only when necessary.
The inner verification loop increments by the current stride, which means fewer iterations for large strides. The moment a mismatch is detected, both the inner and outer stride loops break, preventing unnecessary work.
Appending only the skipped prefix characters, rather than rebuilding the entire palindrome, minimizes memory operations. The while loop appends exactly the characters that are missing, leveraging the already prepared reversed string.
Overall, the combination of early exits, stride-based sampling, and minimal copying yields a solution that scales well for typical input sizes while maintaining correctness across all edge conditions.
ELI5 - Simplified Explanation
Imagine you have a row of colored blocks that spells out a special word. Sometimes the row is not a perfect mirror image of itself. This code is trying to turn that row into a mirror image so that it looks the same when read from the front or the back.
First, the code makes a copy of the blocks and flips them all around so they face the other way. Now the code starts looking for the longest part of the original row that is already a perfect mirror. It tests how many extra blocks need to be added to the front to make the whole thing symmetrical.
The code picks a spot to start and checks the blocks one by one to see if they match up properly. It uses a clever trick by checking different patterns of the blocks, sometimes looking at many blocks at once and other times looking at every single one to be sure they match perfectly. If the blocks do not match, it slides over and tries a different spot.
Once the code finds the right spot where the mirror works, it takes all those extra blocks that were left over and adds them onto the front of the flipped row. This creates one big, perfect line of blocks that reads exactly the same whether you start from the beginning or the end.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Rust | Python | C# | Go | TS | |||
| LeetcodeHelp | C++ | Java | Python | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Java | Python | |||||||
| github | aylei | Rust | ||||||||
| begeekmyfriend | C | |||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| fengvyi | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| gouthampradhan | Java | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| begeekmyfriend | C | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| fengvyi | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| gouthampradhan | Java | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 5: Longest Palindromic Substring
- problem 28: Find the Index of the First Occurrence in a String
- problem 336: Palindrome Pairs
- problem 2430: Maximum Deletions on a String
Solved On The Same Day
- problem 19: Remove Nth Node From End of List
- problem 61: Rotate List
- problem 208: Implement Trie (Prefix Tree)
- problem 739: Daily Temperatures
- problem 23: Merge k Sorted Lists
- problem 1316: Distinct Echo Substrings
- problem 1392: Longest Happy Prefix
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality