C++ 0005.cpp
class Solution {
public:
string longestPalindrome(string s) {
string result;
result += s[0];
for (int i = 0; i < s.size(); i++)
{
// odd
for (int step = 1; ; step++)
{
int left = i - step;
int right = i + step;
if (left < 0 || right == s.size())
break;
if (s[left] != s[right])
break;
if (right - left + 1 > result.size())
result = string(s.begin() + left, s.begin() + right + 1);
}
// even
for (int step = 1; ; step++)
{
int left = i - step + 1;
int right = i + step;
if (left < 0 || right == s.size())
break;
if (s[left] != s[right])
break;
if (right - left + 1 > result.size())
result = string(s.begin() + left, s.begin() + right + 1);
}
}
return result;
}
};
Difficulty
and has an acceptance rate of about 38% (10+ million submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- String
- Two Pointers
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 presented implementation computes the longest palindromic substring of a given input string. It follows the classic “expand-around-center” technique, examining each character as a potential middle point for both odd-length and even-length palindromes. By progressively widening the window while the characters at symmetric positions match, the algorithm captures the maximal palindrome that can be formed around each center and retains the longest one discovered.
Key Steps
Initialization
At the start a result container is prepared and seeded with the first character of the input. This guarantees that the function always returns a non-empty palindrome, even when the input consists of a single character.
string result;
result += s[0];
Expanding Around Center - Odd Length
The outer loop iterates over every index i of the string, treating each position as the centre of a possible odd-length palindrome. An inner loop indexed by step expands outward symmetrically: left = i - step and right = i + step. The expansion stops when either boundary is crossed or the characters at the two ends differ. Whenever a larger palindrome is identified (right - left + 1 > result.size()), the result is replaced with the substring spanning the current window.
for (int i = 0; i < s.size(); i++)
{
// odd
for (int step = 1; ; step++)
{
int left = i - step;
int right = i + step;
if (left < 0 || right == s.size())
break;
if (s[left] != s[right])
break;
if (right - left + 1 > result.size())
result = string(s.begin() + left, s.begin() + right + 1);
}
// ...
}
Expanding Around Center - Even Length
Immediately after handling odd-length cases, the algorithm processes even-length palindromes that have their centre between two adjacent characters. The calculation of left and right is shifted by one position (left = i - step + 1) to reflect this offset. The same termination and update logic applies, ensuring that any longer even-length palindrome replaces the current result.
// even
for (int step = 1; ; step++)
{
int left = i - step + 1;
int right = i + step;
if (left < 0 || right == s.size())
break;
if (s[left] != s[right])
break;
if (right - left + 1 > result.size())
result = string(s.begin() + left, s.begin() + right + 1);
}
Final Return
After all centers have been examined, the function returns the longest palindrome stored in result.
return result;
Edge Cases Handled
The algorithm gracefully manages situations where the expansion reaches the limits of the string. The conditions left < 0 and right == s.size() act as guards, preventing out-of-range accesses and terminating the expansion loop precisely at the string boundaries. This mechanism ensures correct behaviour for inputs where the longest palindrome touches the start or end of the string.
When the input consists of a single character, the initial seeding of result with s[0] yields the correct palindrome without entering any expansion loops, as the outer loop runs but the inner loops break immediately due to boundary checks.
For strings where all characters are identical, each center expands to the full length of the string, and the result is updated to the entire input, demonstrating that the code correctly captures maximal palindromes that span the whole string.
Performance Optimizations
The implementation incorporates several practical optimizations that keep the execution efficient.
First, the expansion loops terminate as soon as a mismatch is detected, avoiding unnecessary comparisons beyond the point where a palindrome can no longer be extended. This early-exit strategy reduces the number of character checks dramatically for strings with limited palindromic structure.
Second, the result string is updated only when a strictly longer palindrome is found. By comparing the current window size (right - left + 1) with result.size(), the code prevents redundant construction of substrings that would not improve the answer, thereby limiting memory allocations.
Third, the use of iterator ranges (s.begin() + left, s.begin() + right + 1) to build the new palindrome leverages the standard library’s ability to create substrings efficiently, without manual copying of individual characters.
Finally, the algorithm processes each character as a centre exactly once for both odd and even cases, ensuring that the total amount of work scales linearly with the number of centres while the inner expansion is bounded by the length of the longest palindrome around each centre. This balanced approach yields a practical runtime for typical input sizes.
ELI5 - Simplified Explanation
Imagine you have a long train of colored blocks lined up in a row, and you want to find the longest part that looks exactly the same whether you look at it from the left or from the right. This is like finding a mirror image. The code starts by picking one block to hold onto. Then, it walks down the line of blocks one by one to see if each spot could be the middle of a special mirror pattern.
To check for a pattern, the code reaches out with two invisible hands starting from the middle spot. One hand moves to the left and the other moves to the right. If the blocks held by both hands have the same color, the code keeps reaching further out. As long as the colors continue to match, the reach gets wider and the pattern grows longer. If the colors do not match or if a hand reaches off the end of the train, the code stops and tucks that pattern away if it is the largest one found so far.
There are two ways to check for these mirror patterns. One way happens when the middle is a single block, making the pattern look like an odd number of blocks. The other way happens when the middle is the space between two blocks, making the pattern look like an even number of blocks. By checking both of these ways at every single stop along the train, the code makes sure that no mirror patterns are missed. After checking the whole line of blocks, the longest pattern saved is what the computer keeps.
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++ | Python | Java | TS | |||||||||||
| WalkCCC | C++ | Python | Java | |||||||||||||
| leetcode.ca | C++ | Python | Java | C# | Rust | JS | C | Go | Nim | PHP | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||||||
| Progiez | C++ | Python | Java | |||||||||||||
| github | aylei | Rust | ||||||||||||||
| begeekmyfriend | C | |||||||||||||||
| BigEggStudy | C# | |||||||||||||||
| black-shadows | C++ | |||||||||||||||
| bujosa | Python | |||||||||||||||
| chandansgowda | Python | |||||||||||||||
| charles-wangkai | Java | |||||||||||||||
| chenyanzhe | C++ | |||||||||||||||
| everthis | JS | |||||||||||||||
| fartem | Ruby | |||||||||||||||
| FelixFan1122 | C# | |||||||||||||||
| fengvyi | C++ | |||||||||||||||
| fsq | Python | |||||||||||||||
| gaosq0604 | Python | |||||||||||||||
| Garvit244 | Python | |||||||||||||||
| halfrost | Go | |||||||||||||||
| haoel | C++ | |||||||||||||||
| JoshCrozier | JS | |||||||||||||||
| keineahnung2345 | C++ | |||||||||||||||
| lennylxx | C++ | |||||||||||||||
| linouk23 | C++ | |||||||||||||||
| lkwq007 | Python | |||||||||||||||
| luangong | C++ | |||||||||||||||
| MacJim | C++ | |||||||||||||||
| martianoff | Scala | |||||||||||||||
| qiyuangong | Java | |||||||||||||||
| ruoru | Rust | |||||||||||||||
| Shamik07 | Dart | |||||||||||||||
| sonugiri1043 | C++ | |||||||||||||||
| suxrobGM | C# | |||||||||||||||
| varunu28 | Java | |||||||||||||||
| vli02 | C | |||||||||||||||
| vthwang | Java | |||||||||||||||
| wisdompeak | C++ | |||||||||||||||
| XiaotaoGuo | C++ | |||||||||||||||
| yuanliu666 | Kotlin | |||||||||||||||
| YuriSpiridonov | Python | |||||||||||||||
| zfang399 | C++ | |||||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||||||
| WalkCCC | C++, Python, Java | |||||||||||||||
| leetcode.ca | C, C++, C#, Go, Java, JavaScript, Nim, PHP, Python, Rust, TypeScript | |||||||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||||||
| Progiez | C++, Java, Python | |||||||||||||||
| aylei | Rust | |||||||||||||||
| begeekmyfriend | C | |||||||||||||||
| BigEggStudy | C# | |||||||||||||||
| black-shadows | C++, C++ | |||||||||||||||
| bujosa | Python | |||||||||||||||
| chandansgowda | Python | |||||||||||||||
| charles-wangkai | Java | |||||||||||||||
| chenyanzhe | C++ | |||||||||||||||
| everthis | JavaScript | |||||||||||||||
| fartem | Ruby | |||||||||||||||
| FelixFan1122 | C# | |||||||||||||||
| fengvyi | C++ | |||||||||||||||
| fsq | Python | |||||||||||||||
| gaosq0604 | Python | |||||||||||||||
| Garvit244 | Python | |||||||||||||||
| halfrost | Go | |||||||||||||||
| haoel | C++ | |||||||||||||||
| JoshCrozier | JavaScript | |||||||||||||||
| keineahnung2345 | C++ | |||||||||||||||
| lennylxx | C++ | |||||||||||||||
| linouk23 | C++ | |||||||||||||||
| lkwq007 | Python | |||||||||||||||
| luangong | C++ | |||||||||||||||
| MacJim | C++ | |||||||||||||||
| martianoff | Scala | |||||||||||||||
| qiyuangong | Java | |||||||||||||||
| ruoru | Rust | |||||||||||||||
| Shamik07 | Dart | |||||||||||||||
| sonugiri1043 | C++ | |||||||||||||||
| suxrobGM | C# | |||||||||||||||
| varunu28 | Java | |||||||||||||||
| vli02 | C | |||||||||||||||
| vthwang | Java | |||||||||||||||
| wisdompeak | C++ | |||||||||||||||
| XiaotaoGuo | C++ | |||||||||||||||
| yuanliu666 | Kotlin | |||||||||||||||
| YuriSpiridonov | Python | |||||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 516: Longest Palindromic Subsequence
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
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