Given a string s, return its longest substring that reads the same forwards and backwards. If several tie for longest, return any one of them.
Examples
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is just as long, and is accepted too.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "andstopsspotsand"
Output: "stopsspots"
Constraints
1 <= s.length <= 1000
s consists of lowercase English letters and digits.
Prerequisites
Dynamic programming — being able to say, in one sentence, what a single cell of your table MEANS. Everything else follows from that sentence. Rolling variables: when a state only looks back one or two steps, the table collapses to a couple of numbers.
How to think about it
1. Grow From Every Center Optimal
Intuition
A palindrome mirrors around its middle: a letter when its length is odd, the gap between two letters when it is even. So stand at a middle and grow outward: while the letters at both ends match, step one further out on each side. We cannot tell where the longest palindrome sits, so grow from every letter and every gap, and keep the longest. Any longest palindrome is accepted when there is a tie.
Algorithm
1. best starts as the empty string. 2. For every center from the first letter to the last: letter = grow(s, center, center), the palindrome around that letter; gap = grow(s, center, center + 1), the one around the gap just after it. 3. Whichever is longer than best becomes the new best. 4. grow(s, left, right): while both arms are inside s and s[left] == s[right], step left one place left and right one place right. When they stop, each arm is one step past the palindrome, so return s[left + 1:right]. 5. Return best.
Time & Space
Time O(n^2): n letters and n gaps to grow from, and each can grow across the whole string. Space O(n): each piece held is at most n letters long.
2. Expand Around Every Center Optimal
Intuition
Every palindrome has a centre — a character for odd lengths, the gap between two for even — and there are only 2n-1 of them. Grow outward from each while the ends match, and the longest span wins. Any longest palindrome is accepted, so ties can go either way; comparing with strictly greater simply keeps the first of equal-length winners.
Algorithm
1. For each index, treat it as an odd centre and as the left of an even centre. 2. Expand while both ends are in range and equal. 3. Record the span when it beats the best strictly.
Time & Space
Time O(n^2). Space O(1). Manacher's algorithm reaches O(n) and is worth naming, not writing.