Explain expand-around-center.
Skip to solutionKEEP THE
mediumDSA
How do you find the longest palindromic substring?
109 views
01
Understand the problem
stringsdpexpand-center
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Expand around each center — every index and every gap between indices — growing outward while characters match, and keep the longest. There are 2n−1 centers, each expansion O(n), so O(n²) time, O(1) space. Manacher's algorithm does it in O(n).
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Expand around center
Run Playgrounddef longest_palindrome(s):
if not s: return ""
start, end = 0, 0
def expand(l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1; r += 1
return l + 1, r - 1
for i in range(len(s)):
for l, r in (expand(i, i), expand(i, i + 1)):
if r - l > end - start:
start, end = l, r
return s[start:end + 1]
# --- demo ---
print(longest_palindrome("babad")) # bab (or aba)
print(longest_palindrome("cbbd")) # bb05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 96 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.