Longest Palindromic Substring

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are given a non-empty string s composed of printable ASCII characters. Find and return the longest unbroken slice (s[i:j]) whose characters read identically from left to right and from right to left.

Character matching is exact and case-sensitive ('A' and 'a' are distinct), and digits or punctuation characters participate on the same footing as letters. Every single-character slice has length 1 and counts as a valid palindrome.

Whenever two or more palindromic slices tie for the greatest length, returning any one of those maximum-length slices is accepted (for example, the earliest match in s).

Implement:

def longest_palindromic_substring(s: str) -> str:

Examples

Example 1

Input:  s = "leveret"
Output: "eve"

Walk-through: Both "eve" (s[1:4]) and "ere" (s[3:6]) read the same in both directions and have length 3. No slice of length 4 or more in "leveret" is symmetric, so "eve" (or "ere") is a valid answer.

Example 2

Input:  s = "mnoonnq"
Output: "noon"

Walk-through: The four-character slice "noon" (s[1:5]) mirrors across the boundary between the two 'o' characters at indices 2 and 3. Every other palindromic slice in "mnoonnq" (such as "oo" or "nn") is shorter.

Example 3

Input:  s = "z"
Output: "z"

Walk-through: A one-character string has only a single non-empty slice, "z", which trivially reads the same in either direction.

Example 4

Input:  s = "kp"
Output: "k"

Walk-through: Because 'k' and 'p' differ, "kp" is not symmetric. The maximum palindrome length is 1, so "k" (or "p") is returned.

Constraints

  • 1 <= len(s) <= 2000
  • s consists of printable ASCII characters.

Step-by-step walkthrough

  1. Restate the goal and tie-breaking rule

    For an input string s with 1 <= len(s) <= 2000, our task is to return a maximum-length unbroken slice s[start:end] that is a palindrome (identical left-to-right and right-to-left).

    • Contiguous slice: Characters must sit side by side in s (unlike a subsequence, skipping middle characters is not allowed).
    • Exact character matching: 'A' and 'a' differ, and digits or punctuation symbols compare just like letters.
    • Minimum length 1: Every individual character is already a length-1 palindrome.
    • Leftmost tie-breaking: Although the statement accepts any maximum-length palindrome, our sample assertions pick the earliest (leftmost) match ("leveret" -> "eve" and "kp" -> "k"), so we will deterministically keep the first longest slice we encounter.
  2. Why checking every substring from scratch is too slow

    A direct brute-force search checks all (i, j) pairs (0 <= i < j <= N), builds piece = s[i:j], and compares piece == piece[::-1].

    There are N * (N + 1) / 2 substrings (O(N^2)), and slicing plus reversing a substring takes up to O(N) work, totaling O(N^3) character operations. At N = 2,000, N^3 / 6 is over 1.3 * 10^9 operations — too slow in Python. Worse, it repeats the exact same inner checks over and over: once we already know "eve" is symmetric, testing "sever" only needs one new outer comparison ('s' == 'r'), not five.

  3. Key idea: expand outward from all 2N - 1 centers

    Every palindrome mirrors around its middle. Depending on whether its length is odd or even, that mirror sits in one of two places:

    Odd-length palindrome ("eve"):         Even-length palindrome ("mnoonnq"):
      center is a character s[c]             center is the gap between s[c] and s[c + 1]
    
          e   [v]   e                        m   n   o  |  o   n   n   q
          <--- c --->                            <----- | ----->
        left=1   right=3                       left=1         right=4
    

    In a string of length N: - There are N character centers (center, center) for odd-length palindromes. - There are N - 1 gap centers (center, center + 1) for even-length palindromes (at center = N - 1, right = N starts out of bounds and stops immediately).

    If we start two pointers (left, right) at a center and step outward (left -= 1, right += 1) as long as s[left] == s[right], we find the longest palindrome centered at that spot. Testing all 2N - 1 centers takes at most O(N) steps per center, dropping total time from O(N^3) to O(N^2) (~2 * 10^6 steps worst case for N = 2,000) and O(1) extra space.

  4. Write the outward expansion helper

    Watch the pointer indices carefully at the moment the while loop stops! Suppose s = "lever" and we expand around 'v' at index 2:

    Index:    0   1   2   3   4
    String:   l   e   v   e   r
    
    Start:            L
                      R           s[2] == s[2] ('v' == 'v') -> step outward
    Step 1:       L       R       s[1] == s[3] ('e' == 'e') -> step outward
    Step 2:   L               R   s[0] != s[4] ('l' != 'r') -> STOP!
    
    Valid palindrome sits inside the mismatched pair: indices 1..3 = s[L + 1 : R] = "eve"
    

    Because the last iteration stepped left one position too far left and right one position too far right, the valid palindrome always starts at left + 1 and ends just before right — the half-open slice (left + 1, right) whose length is right - (left + 1). Even when an even center fails on the very first check (left = c, right = c + 1), (left + 1, right) is (c + 1, c + 1), a harmless empty slice of length 0.

    def expand_around_center(s: str, left: int, right: int) -> Tuple[int, int]:
        """Expand outward from (left, right) while characters match; return slice bounds (start, end)."""
        # Grow the window one character on both sides while indices stay in bounds and match.
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
    
        # The loop stops one step past the palindrome on both ends,
        # so the valid palindrome is the half-open slice s[left + 1 : right].
        return left + 1, right
    
  5. Scan centers left-to-right and track the best slice bounds

    We scan center from 0 to len(s) - 1, checking the odd center (center, center) first and the even gap (center, center + 1) second:

    • Store integer indices (best_start, best_end), slicing s[best_start:best_end] only once at the very end so we never allocate temporary strings inside the loop.
    • Update only on strict >: Centers are visited in strictly increasing midpoint order (0, 0.5, 1, 1.5, ...). Among two palindromes tied for the global maximum length L, the one with the smaller start index also has the smaller midpoint, so we visit it first and strict > prevents any later tie from overwriting it.
    def longest_palindromic_substring(s: str) -> str:
        # Track half-open bounds [best_start, best_end) so we slice `s` only once at the end.
        best_start = 0
        best_end = 0
    
        for center in range(len(s)):
            # Case 1 (odd length, e.g. "eve"): center sits on character s[center].
            odd_start, odd_end = expand_around_center(s, center, center)
            if odd_end - odd_start > best_end - best_start:
                best_start = odd_start
                best_end = odd_end
    
            # Case 2 (even length, e.g. "noon"): center sits in the gap between s[center] and s[center + 1].
            even_start, even_end = expand_around_center(s, center, center + 1)
            # Strict '>' preserves the leftmost palindrome when multiple answers tie for max length.
            if even_end - even_start > best_end - best_start:
                best_start = even_start
                best_end = even_end
    
        return s[best_start:best_end]
    
  6. Trace Example 1 ("leveret") and Example 2 ("mnoonnq")

    Example 1: s = "leveret"
      center=0: odd (0,0) -> [0,1) "l"   (len 1 > 0 -> best=[0,1) "l")
                even(0,1) -> 'l'!='e'    (len 0)
      center=1: odd (1,1) -> [1,2) "e"   (len 1); even(1,2) -> 'e'!='v' (len 0)
      center=2: odd (2,2) -> [1,4) "eve" (len 3 > 1 -> best=[1,4) "eve")
                even(2,3) -> 'v'!='e'    (len 0)
      center=3: odd (3,3) -> [3,4) "e"   (len 1); even(3,4) -> 'e'!='r' (len 0)
      center=4: odd (4,4) -> [3,6) "ere" (len 3 > 3 is False -> keeps "eve"!)
                even(4,5) -> 'r'!='e'    (len 0)
      center=5..6: max len 1
      Result: s[1:4] = "eve"
    
    Example 2: s = "mnoonnq"
      center=0..1: max len 1 (best=[0,1) "m")
      center=2: odd (2,2) -> [2,3) "o" (len 1)
                even(2,3) -> s[2]==s[3]=='o', s[1]==s[4]=='n', s[0]!=s[5] -> [1,5) "noon" (len 4 -> best=[1,5)!)
      center=3: odd (3,3) -> [3,4) "o" (len 1); even(3,4) -> len 0
      center=4: odd (4,4) -> [4,5) "n" (len 1); even(4,5) -> [4,6) "nn" (len 2 < 4)
      center=5..6: max len 1
      Result: s[1:5] = "noon"
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def expand_around_center(s: str, left: int, right: int) -> Tuple[int, int]:
        """Expand outward from (left, right) while characters match; return slice bounds (start, end)."""
        # Grow the window one character on both sides while indices stay in bounds and match.
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
    
        # The loop stops one step past the palindrome on both ends,
        # so the valid palindrome is the half-open slice s[left + 1 : right].
        return left + 1, right
    
    
    def longest_palindromic_substring(s: str) -> str:
        # Track half-open bounds [best_start, best_end) so we slice `s` only once at the end.
        best_start = 0
        best_end = 0
    
        for center in range(len(s)):
            # Case 1 (odd length, e.g. "eve"): center sits on character s[center].
            odd_start, odd_end = expand_around_center(s, center, center)
            if odd_end - odd_start > best_end - best_start:
                best_start = odd_start
                best_end = odd_end
    
            # Case 2 (even length, e.g. "noon"): center sits in the gap between s[center] and s[center + 1].
            even_start, even_end = expand_around_center(s, center, center + 1)
            # Strict '>' preserves the leftmost palindrome when multiple answers tie for max length.
            if even_end - even_start > best_end - best_start:
                best_start = even_start
                best_end = even_end
    
        return s[best_start:best_end]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a palindrome (a string whose characters match identically forward and backward, like "racecar" or "noon") as a strip of paper folded at its exact midpoint so every character on the left lands directly on a matching character on the right. Instead of guessing both outer endpoints of a contiguous substring (an unbroken slice of adjacent characters) from the outside in, you can choose a fold line and step two pointers outward one character at a time while the left and right characters agree. That fold line can sit directly on a character (for odd-length palindromes like "eve") or in the gap between two adjacent characters (for even-length palindromes like "noon").

Why does the obvious brute-force approach fall short? Enumerating all O(N^2) start-and-end pairs and reversing each slice in O(N) takes O(N^3) character comparisons — over a billion operations when N = 2,000 — because it re-verifies the same middle characters from scratch for every wider substring. Expanding outward from each of the 2N - 1 centers reuses that symmetry immediately: one mismatch stops the expansion for that center, cutting total work to O(N^2) time and O(1) extra memory.

Here is how expanding around centers finds the answer on "leveret" (Example 1):

s = "l e v e r e t"   (indices 0..6)

center = 0: odd (0,0) -> "l" [0,1)       | even (0,1) -> 'l'!='e', empty   -> best = "l"
center = 1: odd (1,1) -> "e" [1,2)       | even (1,2) -> 'e'!='v', empty   -> best = "l"
center = 2: odd (2,2) -> 'v', then 'e'=='e' -> "eve" [1,4)                 -> best = "eve"
center = 3: odd (3,3) -> "e" [3,4)       | even (3,4) -> 'e'!='r', empty   -> best = "eve"
center = 4: odd (4,4) -> 'r', then 'e'=='e' -> "ere" [3,6) (tie, keep 1st) -> best = "eve"
center = 5..6: length <= 1                                                 -> best = "eve"

Slice once at the end: s[1:4] -> "eve"

Complexity

Let N be the length of s (1 <= N <= 2,000).

  • Time: O(N^2). For each of the N indices, we run two outward expansions (one odd center, one even gap), and each expansion steps outward at most N / 2 times doing an O(1) character comparison per step. On random text most centers stop after 1–2 comparisons; in the worst case ("aaaa...a"), all 2N - 1 centers expand to a string boundary for roughly N^2 total comparisons (~2 * 10^6 at N = 2,000).
  • Space: O(1) auxiliary space (O(L) for the returned substring of length L). During the search we store only integer index pairs (best_start, best_end) representing a half-open interval [start, end) (an index range that includes start and excludes end, matching Python slice syntax) and slice s once at the very end.

Edge cases

  • Single-character string ("z"): Odd expansion at center = 0 returns (0, 1) ("z"), while even expansion (0, 1) immediately exits the loop and returns (1, 1) (length 0).
  • All characters distinct ("kp", "abcde"): Every odd expansion has length 1 and every even expansion has length 0; strict > keeps the first character ("k" or "a").
  • Even-length answer ("mnoonnq" -> "noon", "xabbay" -> "abba"): Caught by the gap expansion (center, center + 1).
  • Entire string is a palindrome ("racecar"): Expansion from the middle reaches left = -1 and right = len(s), returning (0, len(s)).
  • Case sensitivity and punctuation ("Aba", "12#21!"): 'A' != 'a', while "12#21" matches character for character.
  • Multiple tied maximum-length palindromes ("leveret", "kp"): Visiting centers from left to right and updating only on > deterministically returns the leftmost one.

Common mistakes

  • Forgetting even-length gap centers: Expanding only from (center, center) misses every even-length palindrome and returns "m" on "mnoonnq" instead of "noon".
  • Off-by-one slice bounds after the while loop: When the loop terminates, left and right have already stepped one index past the matching characters (for "eve" at 0..3, left == -1 and right == 3). Returning s[left : right + 1] instead of s[left + 1 : right] includes mismatched characters or wraps around via s[-1:] in Python.
  • Taking the longest common substring of s and s[::-1]: Fails whenever s contains a non-palindromic substring alongside its reversed copy elsewhere — on "abacdfgdcaba", "abacd" appears reversed at the end ("dcaba"), but "abacd" is not a palindrome (the true answer is "aba").
  • Slicing s[left:right] inside the while loop: Allocates new strings repeatedly and can silently inflate runtime toward O(N^3).

Alternative approaches

  • Dynamic programming (O(N^2) time, O(N^2) space): Dynamic programming (solving larger subproblems from cached answers to smaller subproblems) fills a boolean table is_pal[i][j] = (s[i] == s[j]) and is_pal[i + 1][j - 1] by increasing substring length. It matches center expansion's O(N^2) time, but allocates 4 * 10^6 table cells at N = 2,000 instead of O(1) space.
  • Rolling hash + binary search (O(N log N) average time, O(N) space): A rolling hash (a polynomial fingerprint of a sliding substring updated in O(1) time) tests whether s[i:j] matches its reverse in O(1), and binary searching odd lengths and even lengths separately finds the maximum length in O(log N) passes.
  • Manacher's algorithm (O(N) time, O(N) space): Manacher's algorithm (a specialized linear-time palindrome finder that reuses mirror symmetry inside the rightmost palindrome found so far) solves the problem in O(N) time, though it is trickier to code bug-free under interview pressure when N <= 2,000 already passes comfortably in O(N^2).

Follow-up questions

  • How can you improve the worst-case time complexity from O(N^2) to O(N)? Use Manacher's algorithm. First interleave # sentinel characters ("eve" -> "#e#v#e#") so both odd and even palindromes become odd-length centered on a single index, then maintain the rightmost palindrome boundary [L, R] seen so far. Whenever a new center i sits inside [L, R], initialize its radius from its mirror center L + R - i (clamped to R - i) before expanding outward; because R advances rightward at most 2N + 1 times across the entire run, all outward character checks sum to O(N).
  • What changes if you need to count every palindromic substring in s instead of returning the longest one? Every valid palindromic slice has a unique center among the 2N - 1 centers, and each iteration of while left >= 0 and right < len(s) and s[left] == s[right] uncovers one distinct palindrome at that center. Increment count += 1 inside that while loop across all 2N - 1 centers for an O(N^2) time, O(1) space solution (or sum (radius + 1) // 2 over Manacher's #-padded radii in O(N) time).
  • How would your approach change if the selected characters did not need to be adjacent (longest palindromic subsequence)? Outward center expansion breaks when characters can be skipped (for "bbbab", the longest palindromic subsequence is "bbbb" of length 4). Instead, define a dynamic programming table dp[i][j] for the longest palindromic subsequence inside s[i..j]: when s[i] == s[j], dp[i][j] = dp[i + 1][j - 1] + 2, and otherwise dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]), which runs in O(N^2) time and O(N) space when retaining only the previous row.

Follow-up questions

Similar questions

More Intersystems interview questions

All 5 Intersystems questions →