Longest Palindromic Substring
On this page
Problem statement
Given a string, return its longest contiguous substring that reads the same forwards and backwards. If several have the same maximum length, any one of them is accepted.
The standard answer, "expand around every centre", is short, needs O(1) extra space and is what most interviewers expect. The 2D DP and Manacher's algorithm are good things to mention. Original problem: LeetCode 5.
Example

Input: "banana"
Output: "anana"
Input: "xabbay"
Output: "abba"
Input: "q"
Output: "q"
Constraints (assumed)
- 1 ≤ length ≤ 1,000.
- Letters and digits only.
What this question tests
- Using the structure of a palindrome (symmetry around a centre) instead of checking every substring.
- Handling odd and even lengths in one clean loop.
- Index arithmetic: turning the final
lo/hiback into the right substring.
Questions to ask first
- Substring or subsequence? (Substring: contiguous. Longest palindromic subsequence is a different DP.)
- If there are ties, which one? (Here: any.)
- Case sensitive? Spaces and punctuation? (Here: compare characters as they are.)
- How long can the string be? O(n²) is fine for 1,000; ask before reaching for Manacher.
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.