#5

Longest Palindromic Substring

Medium Expand around centre

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the longest substring that is a palindrome.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the longest piece that is a palindrome.

Why this works: every palindrome grows out from a centre (one letter, or a gap between two). Try every centre and expand while both sides match.

Example: "babad"

centre 'a' (index 1): "bab" length 3centre 'b' (index 2): "aba" length 3answer "bab"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Only expanding around single characters, which misses even-length palindromes like "abba".

Solve on LeetCode ↗
Complexity
  • Time: O(n²).
  • Space: O(1).
Topic: Strings
🎬 Episodes 16–20: video coming soon