Skip to content
mlmentorship

Longest Palindromic Substring

Return the longest continuous palindrome in a string.

Published · 4 min read ·Core ·Mixed

30-second answer map

Visual first · depth when needed

Every odd or even palindrome is discovered by expanding its unique center; update the saved range only when an expansion is strictly longer.

Preparing the visual…

ML breadth · active recall

Practice before you read

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

How practice works

ML breadth · closed-book attempt

Longest Palindromic Substring

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

08:00recommended time

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

Return the longest continuous palindrome in a string.

Start with the concrete trace below. It shows the state the algorithm must carry as it runs.

Problem trace

Longest Palindromic Substring: Every odd or even palindrome is discovered by expanding its unique center; update the saved range only when an expansion is strictly longer.

Input and goalReturn the longest continuous palindrome in a string.
Initialize best rangeFor text babad, best_left = best_right = 0, so the initial saved palindrome is b.
best [0,0]b0a1b2a3d4
inputbabadbestRange[0,0] -> b

Recognize it
The answer is a contiguous palindrome, whose symmetry guarantees one unique odd character center or even gap center.
Keep true
Within expand(left,right), text[left:right+1] is palindromic before the pointers move outward. After each completed center, the saved range is the longest palindrome seen at any processed center.
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.
Read it this way: For text babad, best_left = best_right = 0, so the initial saved palindrome is b. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.

Pattern: Expand from every center.

Simple idea: Every palindrome has one center character or a gap between two center characters. Expand both forms at every position and save the longest range.

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: time and space.