Medium · Expand Around Centre
Understand → Visualise → Practice.
Return a longest contiguous substring that reads the same forwards and backwards. If tied, return the earliest one.
Every palindrome has a centre: a character (odd length) or a gap between two characters (even length). Expand outwards from all 2n − 1 centres.
For each i, expand from (i, i) and from (i, i + 1).
Move left and right outwards while the characters match.
Record a palindrome only when it is strictly longer than the best so far.
O(n²) time and O(1) extra space.
Checking only odd centres misses even palindromes such as "abba".
Read the full guide first: Strings: Frequencies, Matching and Palindromes.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.