Problem 5

Abstract / Summary

Find the longest sequence of characters that reads the same forwards and backwards within a given string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};

43 lines | 1150 bytes | submitted August 7, 2023 | GitHub   6% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 38% (10+ million submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 29 | median = 6 | μ = 5.79 | σ = 1.27

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
64 links | 44 authors | 15 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Longest Palindromic Substring - Python - Leetcode 5'
NeetCode 9 mins
Longest Palindromic Substring - Python - Leetcode 5
YouTube video 'LeetCode 5.  Longest Palindromic Substring (Algorithm Explained)'
Nick White 15 mins
LeetCode 5. Longest Palindromic Substring (Algorithm Explained)
YouTube video '8. Longest Palindromic Substring | Leetcode 5 | Strings | Odd and even length approach'
Ayushi Sharma 17 mins
8. Longest Palindromic Substring | Leetcode 5 | Strings | Odd and even length approach
YouTube video 'Longest Palindromic Substring | LeetCode 5 | C++, Java, Python'
Knowledge Center 17 mins
Longest Palindromic Substring | LeetCode 5 | C++, Java, Python
YouTube video '5. Longest Palindromic Substring | Day 001 | Brute - Better - Optimal | 2 Pointers | DP'
Aryan Mittal 22 mins
5. Longest Palindromic Substring | Day 001 | Brute - Better - Optimal | 2 Pointers | DP
YouTube video 'Longest Palindromic Substring O(N) Manacher's Algorithm | Leetcode - 5'
Algorithms Made Easy 16 mins
Longest Palindromic Substring O(N) Manacher's Algorithm | Leetcode - 5
YouTube video 'Leetcode 5. Longest Palindromic Substring'
Code with Alisha 24 mins
Leetcode 5. Longest Palindromic Substring
YouTube video '5. Longest Palindromic Substring|| Java || Leetcode || Hindi'
Coding Sphere 9 mins
5. Longest Palindromic Substring|| Java || Leetcode || Hindi
YouTube video 'Longest Palindromic Substring | Live Coding with Explanation | Leetcode - 5'
Algorithms Made Easy 10 mins
Longest Palindromic Substring | Live Coding with Explanation | Leetcode - 5
YouTube video 'Longest Palindromic Substring LeetCode 5 - This Algorithm Finds Palindromes Like Magic!'
CodingNinja 19 mins
Longest Palindromic Substring LeetCode 5 - This Algorithm Finds Palindromes Like Magic!
YouTube video 'LEETCODE 5 (JAVASCRIPT) | LONGEST PALINDROMIC SUBSTRING | CODING INTERVIEW PREP'
Andy Gala 15 mins
LEETCODE 5 (JAVASCRIPT) | LONGEST PALINDROMIC SUBSTRING | CODING INTERVIEW PREP
YouTube video '[Code] Longest Palindromic Substring | Code explanation | Leetcode 5'
Ayushi Sharma 3 mins
[Code] Longest Palindromic Substring | Code explanation | Leetcode 5
YouTube video 'longest palindromic substring leetcode | leetcode 5 | dp | google | facebook'
Naresh Gupta 12 mins
longest palindromic substring leetcode | leetcode 5 | dp | google | facebook
YouTube video 'Microsoft Interview Question - Longest Palindromic Substring - LeetCode 5'
AlgoJS 8 mins
Microsoft Interview Question - Longest Palindromic Substring - LeetCode 5
YouTube video 'Longest Palindromic Substring Python Solution - LeetCode #5'
Professor Oakes 6 mins
Longest Palindromic Substring Python Solution - LeetCode #5
YouTube video 'LONGEST PALINDROMIC SUBSTRING | LEETCODE # 5 | PYTHON SOLUTION'
Cracking FAANG 12 mins
LONGEST PALINDROMIC SUBSTRING | LEETCODE # 5 | PYTHON SOLUTION
YouTube video 'Longest Palindromic Substring - LeetCode 5 - Blind 75 - Coding Interview'
One Code Man 9 mins
Longest Palindromic Substring - LeetCode 5 - Blind 75 - Coding Interview
YouTube video 'LeetCode 5. Longest Palindromic Substring Explanation and Solution'
happygirlzt 8 mins
LeetCode 5. Longest Palindromic Substring Explanation and Solution
YouTube video 'Leetcode 5: Longest Palindromic Substring in Telugu | Bruteforce, Optimal | Python DSA | SRKCodes'
Srk Codes 14 mins
Leetcode 5: Longest Palindromic Substring in Telugu | Bruteforce, Optimal | Python DSA | SRKCodes
YouTube video 'Longest Palindromic Substring | Brute Force,Expand Around Center | Python Telugu DSA | srkcodes'
Srk Codes 17 mins
Longest Palindromic Substring | Brute Force,Expand Around Center | Python Telugu DSA | srkcodes
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

40 easy 30 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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