15% off all plans & roadmaps Use code

See plans

Longest Palindromic Substring

Updated

TL;DR: Find the longest substring that reads the same forwards and backwards. Expand outward from each of the 2n-1 possible centers and keep the longest match, which runs in O(n^2) time and O(1) space.

Problem

Given a string s, return the longest palindromic substring in s. A palindrome reads the same forwards and backwards. If several answers have the same length, any one of them is accepted.

Example 1

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.

Example 2

Input: s = "cbbd"
Output: "bb"

Constraints

  • 1 <= s.length <= 1000
  • s consists of only digits and English letters.

Constraints that matter

  • s.length <= 1000 means an O(n^2) solution does about 10^6 steps, which is fast. An O(n^3) solution does up to about 10^8 character comparisons, which is slow in interpreted languages.
  • s.length >= 1 means the answer always exists, because any single character is a palindrome. You never return an empty string.
  • Only digits and English letters appear, so every character is one byte and slicing by index is safe in all six languages.
  • Any longest palindrome is accepted on ties, so you may keep the first one found and ignore later palindromes of equal length.

View on LeetCode

Hints

Hint 1

This is an expand-from-center problem, a form of two pointers.

Hint 2

List every substring, test each one for being a palindrome, and keep the longest.

Solution

Intuition

This is an expand-from-center problem, a form of two pointers. A palindrome mirrors around its middle. If you know the middle, you can check the palindrome by walking one pointer left and one pointer right while the characters match.

Picture two people starting at the middle of a line of paired lockers and walking outward together. The middle is the center, each matching pair of lockers is one layer of the palindrome, and the first mismatch is where they stop.

The brute force fixes the two ends of a substring first and then checks the inside. That wastes work, because the substrings s[3..12] and s[4..11] share almost all their characters and the check starts over each time. Fixing the center first turns the check into a growth process. A palindrome of length 10 is a palindrome of length 8 plus one matching pair on the outside.

There are two kinds of center. An odd palindrome like aba has a character in the middle. An even palindrome like abba has a gap between two equal characters. A string of length n has n character centers and n-1 gap centers, so 2n-1 centers in total.

Every palindromic substring has exactly one center, so trying all 2n-1 centers and expanding each as far as it goes cannot miss the answer. Each expansion costs at most n steps. That gives O(n^2) time without any extra table.

Watch the pattern animation

Worked example

Input: s = "forgeeksskeegfor"
Output: "geeksskeeg"
Explanation: The string has 16 characters. The two middle characters at indices 7 and 8 are both 's', and the match keeps growing through k, e, e, g. It stops when 'r' at index 2 meets 'f' at index 13. That leaves indices 3 to 12, which spell "geeksskeeg", a palindrome of length 10.

Approach 1: Brute force

List every substring, test each one for being a palindrome, and keep the longest. A substring is defined by its start i and end j. The test compares the first and last characters, then the second and second to last, and so on.

This is easy to get right and it is the baseline an interviewer expects you to state first. It is also slow, because each of the roughly n^2 / 2 substrings costs up to n / 2 comparisons.

Steps

  1. Set start = 0 and bestLen = 1, since any single character is a palindrome.
  2. Loop i over every start index from 0 to n-1.
  3. Loop j over every end index from i to n-1.
  4. If the length j - i + 1 beats bestLen, test s[i..j] with two pointers moving inward.
  5. If the test passes, store start = i and bestLen = j - i + 1.
  6. Return s[start .. start + bestLen).

Dry run

Run on the example forgeeksskeegfor. The loops visit all 136 substrings. Each candidate that is longer than the current best gets a two-pointer test.

  • i = 0: fo, for and longer substrings starting at 'f' fail on the first or second comparison. The best stays at length 1.
  • i = 4: ee passes, so bestLen = 2 and start = 4.
  • i = 3: geeksskeeg (j = 12) passes after five matching pairs, so bestLen = 10 and start = 3.
  • Every later candidate has length at most 10, so none beats the best. Starts at i = 4 and beyond cannot reach length 11 within a 16-character string.

The loop ends with start = 3 and bestLen = 10, so the result is geeksskeeg.

Complexity

TimeO(n^3)
SpaceO(1)

Let n be the length of s. The two loops produce n * (n + 1) / 2 substrings, which is O(n^2). Each palindrome test runs at most half the substring length, which is O(n). Multiplying gives O(n^3). The code stores only a few integers and compares in place, so extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n = len(s)
        best = s[0]
        for i in range(n):
            for j in range(i, n):
                sub = s[i:j + 1]
                # compare against the reversed copy to test for a palindrome
                if len(sub) > len(best) and sub == sub[::-1]:
                    best = sub
        return best

Approach 2: Dynamic programming table

What's slow: the brute force re-checks the inside of every substring from scratch. The substring s[3..12] contains s[4..11], which contains s[5..10], and each test walks all of those pairs again.

The insight that fixes it: a substring s[i..j] is a palindrome exactly when s[i] == s[j] and the inner substring s[i+1..j-1] is a palindrome. Store that answer in a table dp[i][j] so each substring is decided in O(1) from a smaller one. Substrings of length 1 are always palindromes. Substrings of length 2 and 3 need only s[i] == s[j], because their inner part is empty or a single character.

Steps

  1. Create an n by n boolean table dp, all false.
  2. Loop i from n-1 down to 0, so row i+1 is complete before row i needs it.
  3. Loop j from i to n-1.
  4. Mark dp[i][j] true when s[i] == s[j] and either j - i < 3 or dp[i+1][j-1] is true.
  5. When you mark a cell true and j - i + 1 beats bestLen, record start = i and bestLen.
  6. Return s[start .. start + bestLen).

Dry run

Run on forgeeksskeegfor (n = 16). Rows are filled from i = 15 up to i = 0.

  • Every dp[i][i] is true, so bestLen = 1. The first row that improves it is i = 10: dp[10][11] is true because s[10] == s[11] == 'e' and j - i = 1 < 3. So bestLen = 2, start = 10.
  • Row i = 7: dp[7][8] is true ('s','s'). Then dp[6][9] ('k','k') needs dp[7][8], which is true. Then dp[5][10] needs dp[6][9], then dp[4][11] needs dp[5][10].
  • Row i = 3: dp[3][12] ('g','g') needs dp[4][11], which is true. That sets bestLen = 10, start = 3.
  • Row i = 2: dp[2][13] fails because 'r' is not 'f'. No later cell reaches 11.

The answer is s[3..12] = geeksskeeg.

Complexity

TimeO(n^2)
SpaceO(n^2)

Let n be the length of s. The table has n * n cells and each cell is computed with one comparison and one table lookup, so time is O(n^2). The table itself holds n * n booleans, so space is O(n^2). For n = 1000 that is one million cells, which fits comfortably.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n = len(s)
        dp = [[False] * n for _ in range(n)]
        start, best = 0, 1
        for i in range(n - 1, -1, -1):
            for j in range(i, n):
                # inner part is empty or one char when j - i < 3
                if s[i] == s[j] and (j - i < 3 or dp[i + 1][j - 1]):
                    dp[i][j] = True
                    # >= so ties prefer the earliest start (i decreases)
                    if j - i + 1 >= best:
                        best = j - i + 1
                        start = i
        return s[start:start + best]
Expanding From Center (Palindromes) pattern infographic for Longest Palindromic Substring

Solution pattern

Expanding From Center (Palindromes)

Part of Two Pointers

Approach 3: Expand around each centerOptimalExpanding From Center (Palindromes)

What's slow: the DP table stores n * n answers, but most of them are false, and you only ever read the cell diagonally inside the current one. The memory is far larger than the information you need.

The insight that fixes it: a palindrome grows from its center one matching pair at a time, so you do not need a table at all. For each of the 2n-1 centers, put a left pointer and a right pointer on it and move them apart while s[left] == s[right]. When the loop stops, the palindrome is the range strictly between the pointers, with length right - left - 1. Keep the best start and length seen so far.

Why it is correct. Any palindrome around a given center is built from nested pairs of equal characters, so it must contain every inner pair. The first mismatch therefore caps the palindrome at that center, and no longer one can exist there. Since every palindromic substring has exactly one center, checking all centers and keeping the best length finds the global maximum.

Steps

  1. Set start = 0 and bestLen = 1.
  2. For each index i, run expand(i, i) for the odd palindrome centered on a character.
  3. For the same i, run expand(i, i + 1) for the even palindrome centered on the gap after i.
  4. Inside expand, loop while left >= 0, right < n and s[left] == s[right], moving left down and right up.
  5. Return right - left - 1 from expand, since both pointers have stepped one place past the palindrome.
  6. Take the larger of the two lengths. If it beats bestLen, set bestLen and start = i - (len - 1) / 2 using integer division.
  7. Return s[start .. start + bestLen).

Dry run

Run on forgeeksskeegfor. Each row shows the lengths found for the odd center i and the even center between i and i + 1.

icharodd lengtheven lengthbest lengthstart
0f1010
1o1010
2r1010
3g1010
4e12 (e,e at 4,5)24
5e1024
6k1024
7s110 (s,k,e,e,g pairs)103
8s10103
9k10103
10e12103
11e10103
12g10103
13 to 15f, o, r10103

At i = 7 the even expansion starts with left = 7, right = 8. It matches five pairs: (7,8), (6,9), (5,10), (4,11), (3,12). Then it stops at left = 2, right = 13 because 'r' is not 'f'.

The length is 13 - 2 - 1 = 10, and start = 7 - (10 - 1) / 2 = 7 - 4 = 3. The result is s[3..12] = geeksskeeg.

Complexity

TimeO(n^2)
SpaceO(1)

Let n be the length of s. There are 2n-1 centers, and each expansion moves the pointers at most n / 2 steps outward before hitting a boundary. Total work is at most (2n-1) * n / 2, which is O(n^2). The worst case is a string like aaaa...a, where every expansion runs to the boundary. Only a handful of integers are stored, so extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def longestPalindrome(self, s: str) -> str:
        start, best = 0, 1
        for i in range(len(s)):
            odd = self.expand(s, i, i)
            even = self.expand(s, i, i + 1)
            length = max(odd, even)
            if length > best:
                best = length
                start = i - (length - 1) // 2
        return s[start:start + best]

    def expand(self, s: str, left: int, right: int) -> int:
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        # both pointers are one step outside the palindrome
        return right - left - 1

Common mistakes

  • Only calling expand(i, i). This finds odd palindromes and misses bb and abba. Add the second call expand(i, i + 1) for every i.
  • Returning right - left + 1 from expand. The loop exits after the pointers have stepped one place past the palindrome on each side. The correct length is right - left - 1.
  • Computing the start as i - len / 2. For an even length this is off by one. Use i - (len - 1) / 2 with integer division, which works for both odd and even lengths.
  • Putting s[left] == s[right] before the bounds checks in the while condition. You read index -1 or n and crash in Java, C# and Go, or compare against undefined in JavaScript. Check left >= 0 and right < n first.
  • Setting bestLen = 0 and starting start at 0 for a one-character string. If the update uses >, the answer can come back empty. Start with bestLen = 1, or make sure the first expansion always updates.
  • In the DP, looping i upward from 0. Cell dp[i][j] reads dp[i+1][j-1], which is not filled yet. Loop i from n-1 down to 0, or iterate by substring length.

Edge cases

  • s = "a": the answer is "a". Both expansions run, but only the odd one succeeds, and bestLen = 1 is already correct.
  • s = "bb": the answer is "bb". Only the even center at i = 0 finds it, so this tests that you handle even palindromes.
  • s = "ab": no pair matches, so the answer is any single character. Returning "a" is correct.
  • s = "aaaa...a" with 1000 characters: the whole string is a palindrome and every expansion runs to the boundary. This is the worst case for time, and the answer is the full string.
  • s = "cbbd": the answer is "bb". The even center between indices 1 and 2 matches, then 'c' against 'd' stops it.
  • s = "babad": both "bab" and "aba" are valid. Using a strict > for updates returns "bab", the first one found.

Follow-ups interviewers ask

Can you do better than O(n^2) time?
Yes. Manacher's algorithm finds the longest palindrome around every center in O(n) total time. It reuses the radii of palindromes already found. Inside a big palindrome, the radius at a mirrored position gives a starting guess, so the pointers never re-scan characters they have already confirmed. You insert a separator between characters so odd and even centers become one case. It is rarely required in an interview, but you should be able to name it and sketch the mirror idea.
What if you must count all palindromic substrings instead of finding the longest?
Use the same 2n-1 centers. Each successful expansion step from a center is one new palindrome, so you add one to a counter every time the pointers match. The total time is still O(n^2) and the space is O(1). This is the problem Palindromic Substrings, LeetCode 647.
What if the string is too large to fit in memory?
Expansion needs random access around the current center, so you cannot stream it one pass in the plain form. You can process it in overlapping windows. Each window must be at least as long as twice the longest palindrome you expect, so a palindrome crossing a window boundary still lands fully inside the next window. Manacher's algorithm keeps only the current radius array for a window, which makes it the natural choice for that setting.

Longest Palindromic Substring FAQ

What is the time complexity of Longest Palindromic Substring?

The expand-around-center solution is O(n^2) time and O(1) space. There are 2n-1 centers and each expansion takes at most n / 2 steps. The brute force is O(n^3), the DP table is O(n^2) time and O(n^2) space, and Manacher's algorithm reaches O(n).

Why use expand from center for Longest Palindromic Substring?

A palindrome is defined by its center, and it grows by one matching pair at a time. Expanding from each center reuses the work already done for the smaller palindrome inside it. This gets the speed of the DP table without storing the table.

Can Longest Palindromic Substring be solved in O(1) extra space?

Yes, in O(n^2) time. Expand around center keeps only a few integers, plus the returned substring. The O(n) time Manacher's algorithm needs an array of radii, so it uses O(n) extra space.

Why does the expand function return right - left - 1?

The loop stops when the characters differ or a pointer leaves the string. At that moment left is one place before the palindrome and right is one place after it. The palindrome occupies indices left + 1 through right - 1, which is right - left - 1 characters.

What is the difference between a palindromic substring and a palindromic subsequence?

A substring must be contiguous. A subsequence can skip characters while keeping their order. This page solves the substring version, which is LeetCode 5. The subsequence version is a different problem and uses a DP over two indices.

How do I solve Longest Palindromic Substring in Python or Java?

The three approaches above work in both languages with the same structure. In Python, return s[start:start + best]. In Java, return s.substring(start, start + best). Both languages use half-open ranges, so no extra adjustment is needed.

Asked at

See which companies ask this — Pro

Practise it