← DSA
MEDIUM

Longest Palindromic Substring

PracticeNeetCode ↗LeetCode ↗

Given a string s, return the longest substring of s that reads the same forwards and backwards.

Example

Input s = "babad"
Output "bab"

Key Pointers

Step-by-Step Analysis

  1. Write a helper that, given a left and right pointer, expands outward while the characters match, then reports the (start, length) of the palindrome found.
  2. For each index i, expand around the odd center (left = i, right = i) and the even center (left = i, right = i+1).
  3. After each expansion, compare its length to the best found so far and keep the longer one.
  4. Return the substring described by the best (start, length) across every center.

Complexity

Time: O(n²) — Space: O(1) extra, excluding the returned substring

Code

def longestPalindrome(s: str) -> str:
    start, best_len = 0, 0

    def expand(left: int, right: int) -> None:
        nonlocal start, best_len
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        length = right - left - 1
        if length > best_len:
            best_len = length
            start = left + 1

    for i in range(len(s)):
        expand(i, i)
        expand(i, i + 1)

    return s[start : start + best_len]

Code Explanation

How the solution above works, piece by piece.

  1. Every palindrome mirrors around a centre: a single character (odd length) or the gap between two characters (even length).
  2. For each index, expand(i, i) and expand(i, i + 1) try both kinds of centre.
  3. expand grows outward while the characters on both sides match; when it stops, the palindrome is s[left+1 : right], of length right - left - 1.
  4. Keep the start and length of the longest one found.
  5. 2n centres × up to n expansion each: O(n²) time, O(1) space.

Visual Walkthrough

Running it on s = "babad":

traceb0a1b2a3d4centre i=0"b" length 1 → new bestbabadcentre i=1"bab" length 3 → new best
Only the expansions that set a new record are shown. Centre 1 expands to "bab" (length 3); centre 2 finds "aba", also length 3, which doesn't beat it, so "bab" is returned.
palindrome found

Video Explanation

NeetCode — LeetCode 5