You are given a string s. A palindrome reads the same from left to right as from right to left, like level or 2112.
Return the longest run of consecutive characters in s that is a palindrome. If several share the longest length, any one of them is accepted.
Example 1
Input: s = "tracecar" Output: "racecar" Why: the last seven characters mirror around the e
2 more examples and the constraints
Example 2
Input: s = "cbaab" Output: "baab" Why: an even palindrome: its center is the gap between the two a's
Example 3
Input: s = "z" Output: "z" Why: one character is always a palindrome
Constraints
- 1 ≤ length of s ≤ 1,000
sholds only English letters (upper or lower case) and digits
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every substringO(n³)
- Dynamic programming tableO(n²)
- Expand around each centerO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 characters | Verdict |
|---|---|---|---|
| Check every substring | O(n³) | Too slow at the limit | |
| Dynamic programming table | O(n²) | Passes; uses n² memory | |
| Expand around each center | O(n²) | Best; no extra memory |
n = length of s.
Edge cases to test
- One character. "z" is its own answer. Starting
bestat 1 covers it. - Even length. "cbaab" has no odd palindrome longer than 1. Forgetting the gap centers returns "c" instead of "baab".
- All the same letter. "aaaa" is a palindrome end to end; the expansion must be allowed to reach both edges.
- Case matters. "A" and "a" are different characters, so "AbcbaA9" gives "bcb", not a longer run that only matches when case is ignored.
Common mistakes
- Only trying character centers, which misses every even-length palindrome.
- Off-by-one when cutting the answer: after the loop, lo and hi sit one step past the palindrome, so it is s[lo + 1 .. hi − 1].
- Filling the DP table with i going up, so
pal[i + 1][j − 1]is read before it has been computed.
How to talk through it
- 1Clarify. Substring means consecutive characters, right? Is case significant? If there is a tie, can I return any one?
- 2Give the brute force. Check every substring; say it is O(n³) and why that is too slow for 1,000 characters.
- 3Spot the repeated work. A palindrome minus its two ends is still a palindrome. That gives the DP, and read from the inside out, the center expansion.
- 4Code the expansion. Loop over 2n − 1 centers so odd and even lengths share one loop. Say where lo and hi end up.
- 5Test out loud. Run "z", "cbaab" for the even case and "aaaa" for a palindrome that touches both ends.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?