mediumDSA

How do you find the longest palindromic substring?

109 views
01

Understand the problem

Explain expand-around-center.

stringsdpexpand-center
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Expand around center
Run Playground
def 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"))    # bb
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.