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) <= 2000sconsists of printable ASCII characters.
Step-by-step walkthrough
Restate the goal and tie-breaking rule
For an input string
swith1 <= len(s) <= 2000, our task is to return a maximum-length unbroken slices[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-1palindrome. - 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.
- Contiguous slice: Characters must sit side by side in
Why checking every substring from scratch is too slow
A direct brute-force search checks all
(i, j)pairs (0 <= i < j <= N), buildspiece = s[i:j], and comparespiece == piece[::-1].There are
N * (N + 1) / 2substrings (O(N^2)), and slicing plus reversing a substring takes up toO(N)work, totalingO(N^3)character operations. AtN = 2,000,N^3 / 6is over1.3 * 10^9operations — 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.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=4In a string of length
N: - There areNcharacter centers(center, center)for odd-length palindromes. - There areN - 1gap centers(center, center + 1)for even-length palindromes (atcenter = N - 1,right = Nstarts 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 ass[left] == s[right], we find the longest palindrome centered at that spot. Testing all2N - 1centers takes at mostO(N)steps per center, dropping total time fromO(N^3)toO(N^2)(~2 * 10^6steps worst case forN = 2,000) andO(1)extra space.Write the outward expansion helper
Watch the pointer indices carefully at the moment the
whileloop stops! Supposes = "lever"and we expand around'v'at index2: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
leftone position too far left andrightone position too far right, the valid palindrome always starts atleft + 1and ends just beforeright— the half-open slice(left + 1, right)whose length isright - (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 length0.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, rightScan centers left-to-right and track the best slice bounds
We scan
centerfrom0tolen(s) - 1, checking the odd center(center, center)first and the even gap(center, center + 1)second:- Store integer indices
(best_start, best_end), slicings[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 lengthL, 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]- Store integer indices
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"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 theNindices, we run two outward expansions (one odd center, one even gap), and each expansion steps outward at mostN / 2times doing anO(1)character comparison per step. On random text most centers stop after 1–2 comparisons; in the worst case ("aaaa...a"), all2N - 1centers expand to a string boundary for roughlyN^2total comparisons (~2 * 10^6atN = 2,000). - Space:
O(1)auxiliary space (O(L)for the returned substring of lengthL). During the search we store only integer index pairs(best_start, best_end)representing a half-open interval[start, end)(an index range that includesstartand excludesend, matching Python slice syntax) and slicesonce at the very end.
Edge cases
- Single-character string (
"z"): Odd expansion atcenter = 0returns(0, 1)("z"), while even expansion(0, 1)immediately exits the loop and returns(1, 1)(length0). - All characters distinct (
"kp","abcde"): Every odd expansion has length1and every even expansion has length0; 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 reachesleft = -1andright = 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
whileloop: When the loop terminates,leftandrighthave already stepped one index past the matching characters (for"eve"at0..3,left == -1andright == 3). Returnings[left : right + 1]instead ofs[left + 1 : right]includes mismatched characters or wraps around vias[-1:]in Python. - Taking the longest common substring of
sands[::-1]: Fails wheneverscontains 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 thewhileloop: Allocates new strings repeatedly and can silently inflate runtime towardO(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 tableis_pal[i][j] = (s[i] == s[j]) and is_pal[i + 1][j - 1]by increasing substring length. It matches center expansion'sO(N^2)time, but allocates4 * 10^6table cells atN = 2,000instead ofO(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 inO(1)time) tests whethers[i:j]matches its reverse inO(1), and binary searching odd lengths and even lengths separately finds the maximum length inO(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 inO(N)time, though it is trickier to code bug-free under interview pressure whenN <= 2,000already passes comfortably inO(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 centerisits inside[L, R], initialize its radius from its mirror centerL + R - i(clamped toR - i) before expanding outward; becauseRadvances rightward at most2N + 1times across the entire run, all outward character checks sum toO(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 - 1centers, and each iteration ofwhile left >= 0 and right < len(s) and s[left] == s[right]uncovers one distinct palindrome at that center. Incrementcount += 1inside thatwhileloop across all2N - 1centers for anO(N^2)time,O(1)space solution (or sum(radius + 1) // 2over Manacher's#-padded radii inO(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 length4). Instead, define a dynamic programming tabledp[i][j]for the longest palindromic subsequence insides[i..j]: whens[i] == s[j],dp[i][j] = dp[i + 1][j - 1] + 2, and otherwisedp[i][j] = max(dp[i + 1][j], dp[i][j - 1]), which runs inO(N^2)time andO(N)space when retaining only the previous row.
Follow-up questions
- How can you improve the worst-case time complexity from O(N^2) to O(N)?
- What changes if you need to count every palindromic substring in s instead of returning the longest one?
- How would your approach change if the selected characters did not need to be adjacent (longest palindromic subsequence)?
Similar questions
- Forty-Five-Minute Two-Cord Timer
- Descending Key Map Accumulator
- Safely Extract Inner XML Attributes from CDATA Envelopes
- Delivering a Beginner-Friendly Computer Networking Mini-Lesson
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger