← Back to Algorithms, page 1

algorithms-0020 · Medium mid

Longest palindromic substring: find the longest contiguous substring that is a palindrome.

Every palindrome has a centre, either one character (odd length) or the gap between two characters (even length). For each of the 2n - 1 centres, expand outwards while the characters match, and keep the longest window. This is O(n^2) time and O(1) space, simpler than the O(n^2) DP table and fast enough for typical limits; Manacher's algorithm achieves O(n).

Full answer

Problem

Given s, return the longest substring that reads the same both ways. If several have the same length, any one is accepted.

Example: "babad" gives "bab" (or "aba"); "cbbd" gives "bb".

Constraints: 1 <= len(s) <= 1000, letters and digits.

Brute force

Check every substring with a reverse comparison: O(n^2) substrings, O(n) per check, O(n^3) total.

Dynamic programming

is_pal[i][j] is true if s[i] == s[j] and is_pal[i + 1][j - 1] is true (or the substring has length at most 2). O(n^2) time and O(n^2) space.

Optimal approach: expand around centre

For each index c, expand from (c, c) for odd lengths and from (c, c + 1) for even lengths. While lo >= 0, hi < n and s[lo] == s[hi], move outward. The last valid window is s[lo + 1 : hi]. Keep the longest.

Why it works

A palindrome stays a palindrome when you remove its outer characters, so every palindrome can be grown from its centre one step at a time. Trying all 2n - 1 centres covers every palindrome, and expanding as far as possible from each centre finds the longest palindrome with that centre.

Complexity

O(n^2) time in the worst case (for example "aaaa...a"), O(1) extra space. Manacher's algorithm reuses the mirror image of earlier expansions to reach O(n); it is rarely expected in interviews, but naming it shows depth.

Code

python
def longest_palindrome(s):
    """Expand around each of the 2n - 1 centres. O(n^2) time, O(1) extra space."""
    if not s:
        return ""
    start, end = 0, 0                        # best window s[start:end + 1]

    def expand(lo, hi):
        while lo >= 0 and hi < len(s) and s[lo] == s[hi]:
            lo -= 1
            hi += 1
        return lo + 1, hi - 1                # last valid window

    for c in range(len(s)):
        for lo, hi in (expand(c, c), expand(c, c + 1)):   # odd and even lengths
            if hi - lo > end - start:
                start, end = lo, hi
    return s[start:end + 1]


def is_pal(t):
    return t == t[::-1]


if __name__ == "__main__":
    assert longest_palindrome("babad") in ("bab", "aba")
    assert longest_palindrome("cbbd") == "bb"
    assert longest_palindrome("a") == "a"
    assert longest_palindrome("") == ""
    assert longest_palindrome("forgeeksskeegfor") == "geeksskeeg"
    assert longest_palindrome("abcd") in ("a", "b", "c", "d")
    assert is_pal(longest_palindrome("abacdfgdcaba"))
    print("all tests passed")

Save as a20_longest_palindromic_substring.py and run python3 a20_longest_palindromic_substring.py. It prints all tests passed (Python 3.13.5).

Edge cases

Single character. Empty string (returns ""). All characters equal (the whole string). No repeated characters (any single character). Even-length answers such as "bb", which a centre-only-on-characters approach would miss.

Pattern

Expand around centre, a two-pointer pattern moving outward. It also counts all palindromic substrings (add the number of successful expansions at each centre).

python
def longest_palindrome(s):
    """Expand around each of the 2n - 1 centres. O(n^2) time, O(1) extra space."""
    if not s:
        return ""
    start, end = 0, 0                        # best window s[start:end + 1]

    def expand(lo, hi):
        while lo >= 0 and hi < len(s) and s[lo] == s[hi]:
            lo -= 1
            hi += 1
        return lo + 1, hi - 1                # last valid window

    for c in range(len(s)):
        for lo, hi in (expand(c, c), expand(c, c + 1)):   # odd and even lengths
            if hi - lo > end - start:
                start, end = lo, hi
    return s[start:end + 1]


def is_pal(t):
    return t == t[::-1]


if __name__ == "__main__":
    assert longest_palindrome("babad") in ("bab", "aba")
    assert longest_palindrome("cbbd") == "bb"
    assert longest_palindrome("a") == "a"
    assert longest_palindrome("") == ""
    assert longest_palindrome("forgeeksskeegfor") == "geeksskeeg"
    assert longest_palindrome("abcd") in ("a", "b", "c", "d")
    assert is_pal(longest_palindrome("abacdfgdcaba"))
    print("all tests passed")

Expand-around-centre for odd and even centres; tests accept any valid answer when there is a tie.

Complexity

Time: O(n^2) worst case. Space: O(1) extra. Manacher's algorithm gives O(n) time; the DP table gives O(n^2) time and space.

By level

Fresher: Explains the centre idea and implements the odd-length case, then adds even-length centres after testing "cbbd". Should test a string of length 1 and a string with no repeated letters.

Mid: Implements both centres cleanly, compares with the DP table and handles ties and empty input. Explains why the expansion method uses O(1) extra space.

Senior: Explains Manacher's idea, discusses substring versus subsequence variants and the cost profile for long, repetitive strings. Mentions Manacher's algorithm for O(n).

Key points

  • Every palindrome has an odd or even centre
  • There are 2n - 1 centres
  • Expand while the ends match
  • O(n^2) time, O(1) space
  • Manacher's algorithm achieves O(n)

Common mistakes

  • Forgetting even-length centres
  • Off-by-one when slicing the final window
  • Using the O(n^2)-space DP when O(1) space is easy
  • Confusing substring with subsequence

Follow-ups

  • How would you count all palindromic substrings?
  • What is the longest palindromic subsequence, and how does it differ?
  • How does Manacher's algorithm reuse work?

Tips

  • Mention both centre types early
  • Compare with the DP table briefly
  • Test an even-length answer

Evaluation rubric

  • Correct expand-around-centre solution
  • Handles even and odd lengths
  • Correct complexity
  • Mentions alternatives