Skip to content
mlmentorship

Longest Palindromic Substring

Expand matching endpoints around character and gap centers, retain the first longest range, and adapt the result to ties or repeated interval queries.

Published · 14 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Longest Palindromic Substring

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A Python string text. Output. Return a longest palindromic substring, not merely its length. Rules. The selected characters must be contiguous; skipping intervening characters is not allowed. Use exact code-point equality, without case conversion, Unicode normalization, or grapheme grouping. Any longest palindrome is valid; the reference retains its first equal-length answer. Leave the string unchanged. Empty input returns "". Example. "babad" permits "bab" or "aba"; the reference returns "bab". For "cbbd", return "bb".

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Expand every character center and every gap center. Save only a strictly longer accepted range.

Problem trace

A center replaces the saved palindrome only when it finds a longer one

Input and goalReturn the longest continuous palindrome in a string.
Initialize best rangeFor babad, save inclusive [0,0], the first b. The underline uses half-open range [0,1).
mb0a1b2a3d4
inputbabadbestRange[0,1) = bevenContrastcbbd: gap at 1/2 accepts [1,3) = bb
m
0
input
babad
best range
[0,1) = b

Recognize it
The answer is a contiguous palindrome, whose symmetry guarantees one unique odd character center or even gap center.
Keep true
A successful guard certifies text[left:right+1] before updates. After the pointers move, the next candidate is untested. After each center, the saved range is a longest accepted range so far.
Reuse it
When validity is symmetric around a center, enumerate both center types and expand until the invariant breaks; change only the aggregation to find a longest value, count all values, or validate radii.
For babad, save inclusive [0,0], the first b. The underline uses half-open range [0,1). Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does the final center at d not replace bab? Why does equal-length aba leave the saved answer unchanged?
Full interview answer 14 min read

Return a longest contiguous piece of a string that reads identically forward and backward.

Problem

Input. A Python string text.

Output. Return a longest palindromic substring, not merely its length.

Rules. The selected characters must be contiguous; skipping intervening characters is not allowed. Use exact code-point equality, without case conversion, Unicode normalization, or grapheme grouping. Any longest palindrome is valid; the reference retains its first equal-length answer. Leave the string unchanged. Empty input returns "".

Example. "babad" permits "bab" or "aba"; the reference returns "bab". For "cbbd", return "bb".

Picture

An odd palindrome has a character center. An even palindrome has a gap center:

TextCenterAccepted inclusive rangesStop
babadCharacter one[1,1] is a, then [0,2] is babNext radius exceeds bounds
babadCharacter two[2,2] is b, then [1,3] is abaNext endpoints b and d differ
cbbdGap between one and two[1,2] is bbOuter c and d differ

Every nonempty palindromic range has exactly one midpoint and radius. Trying both center types therefore covers every answer. Matching endpoints extend an already-palindromic inner range. A singleton or empty gap supplies the first inner case. On mismatch, every larger radius still contains that unequal pair. Bounds failure also forbids any larger range at that center.

middle selects a center. left and right are inclusive candidate endpoints. The while guard certifies the current candidate before saving it. Moving outward creates an unchecked candidate, not another proven palindrome.

best_left and best_right retain the longest accepted range across completed centers. The code compares right-left, which is length minus one. Strict > saves bab and keeps it when aba ties.

In the visual, m marks the center and aL/aR mark accepted odd endpoints. The underline preserves the best half-open range. Final bL/bR mark the saved return range, not the last center’s d.

Problem trace

Separate level/aba comparison: a shorter later result cannot replace the best

Worked example: a shorter new palindrome cannot replace the saved bestA saved palindrome of length 5 remains best when a later center finds length 3. Update only when the new length is strictly larger under this tie rule.A later shorter palindrome does notreplace the saved bestInput order: level, abaBlue: current; green: saved best1250Checkpoint numberCurrent: 5, 3Saved: 5, 5
Read it this way: A saved palindrome of length 5 remains best when a later center finds length 3. Update only when the new length is strictly larger under this tie rule. Does finding aba later make the earlier level witness cease to be a palindrome?
Reference drawing

Problem trace

A center replaces the saved palindrome only when it finds a longer one

Worked example: a shorter new palindrome cannot replace the saved bestA saved palindrome of length 5 remains best when a later center finds length 3. Update only when the new length is strictly larger under this tie rule.A later shorter palindrome does notreplace the saved bestInput order: level, abaBlue: current; green: saved best1250Checkpoint numberCurrent: 5, 3Saved: 5, 5
Execution trace
Input and goalReturn the longest continuous palindrome in a string.
Initialize best rangeFor babad, save inclusive [0,0], the first b. The underline uses half-open range [0,1).
mb0a1b2a3d4
inputbabadbestRange[0,1) = bevenContrastcbbd: gap at 1/2 accepts [1,3) = bb
m
0
input
babad
best range
[0,1) = b

Recognize it
The answer is a contiguous palindrome, whose symmetry guarantees one unique odd character center or even gap center.
Keep true
A successful guard certifies text[left:right+1] before updates. After the pointers move, the next candidate is untested. After each center, the saved range is a longest accepted range so far.
Reuse it
When validity is symmetric around a center, enumerate both center types and expand until the invariant breaks; change only the aggregation to find a longest value, count all values, or validate radii.
For babad, save inclusive [0,0], the first b. The underline uses half-open range [0,1). Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does the final center at d not replace bab? Why does equal-length aba leave the saved answer unchanged?
Read it this way: A saved palindrome of length 5 remains best when a later center finds length 3. Update only when the new length is strictly larger under this tie rule. Does finding aba later make the earlier level witness cease to be a palindrome?

Code

def longest_palindrome(text: str) -> str:
   best_left = best_right = 0

   def expand(left: int, right: int) -> None:
      nonlocal best_left, best_right
      while left >= 0 and right < len(text) and text[left] == text[right]:
         if right - left > best_right - best_left:
            best_left, best_right = left, right
         left -= 1
         right += 1

   for middle in range(len(text)):
      expand(middle, middle)
      expand(middle, middle + 1)
   return text[best_left : best_right + 1]

Cost: worst-case comparisons and auxiliary pointer/count slots. The returned slice allocates space for answer length . On empty input, slicing returns ""; initialized [0,0] does not imply an existing character.

Change the Saved Result or the Workload

Start from longest_palindrome. Change either tie retention or the need to answer many range queries.

  1. Keep every longest occurrence.

    New task: Return all maximum-length half-open ranges, not only the first copied text.

    Picture and change: Reset saved ranges on a longer candidate. Append on an equal length; unique centers prevent duplicate ranges.

    Code: Complete replacement:

    def longest_palindrome_ranges(text):
       ranges, best_length = [], 0
       for middle in range(len(text)):
          for left, right in ((middle, middle), (middle, middle + 1)):
             while left >= 0 and right < len(text) and text[left] == text[right]:
                length = right - left + 1
                if length > best_length:
                   ranges, best_length = [[left, right + 1]], length
                elif length == best_length:
                   ranges.append([left, right + 1])
                left -= 1
                right += 1
       return sorted(ranges)

    Check: babad returns [[0,3],[1,4]]; cbbd returns [[1,3]]. Empty input returns [].

    Use when: Tied occurrence witnesses matter. Saved candidates require up to ranges; sorting final ties adds work.

  2. Answer many interval queries.

    New task: Decide whether each supplied half-open range is palindromic.

    Picture and change: Store answers for inner intervals instead of discarding them after expansion. Descending left solves row left+1 first. Equal endpoints extend its inner answer; lengths one and two need no lookup.

    Code: Complete replacement. Queries must satisfy 0 <= left <= end <= len(text):

    def palindrome_queries(text, ranges):
       size = len(text)
       table = [[False] * size for _ in range(size)]
       for left in range(size - 1, -1, -1):
          for right in range(left, size):
             table[left][right] = text[left] == text[right] and (
                right - left < 2 or table[left + 1][right - 1]
             )
       return [True if left == end else table[left][end - 1] for left, end in ranges]

    Check: babad with [[0,3],[1,4],[0,5],[2,2]] gives [True,True,False,True]. Empty ranges are palindromic here.

    Use when: Repeated decisions justify preprocessing and table storage, then per query, plus returned answers.

Rebuild the Aggregation

What changes when the task asks for all palindrome occurrences?

Answer: Keep the same center enumeration. Add one for each accepted radius instead of retaining only a longest range.