Longest Palindromic Substring
Problem Statement
Given a string s, return the longest palindromic substring in s.
Constraints:
- 1 <= s.length <= 1000
- s consist of only digits and English letters.
Input Format:
- A string s
Output Format:
- The longest palindromic substring
Examples:
Example 1:
Input:
s = "babad"
Output:
"bab"
Explanation:
"aba" is also a valid answer.
Example 2:
Input:
s = "cbbd"
Output:
"bb"
Explanation:
The longest palindromic substring is "bb".
Example 3:
Input:
s = "a"
Output:
"a"
Explanation:
A single character is always a palindrome.
Solutions
Expand Around Center
Check each position as a potential center and expand outwards.
Dynamic Programming
Use a 2D array to track whether each substring is a palindrome.
Algorithm Walkthrough
Example input:
Step-by-step execution:
- Input: s = "babad"
- Initialize start = 0, maxLength = 1
- Iterate through each position as potential palindrome center:
- i = 0, character 'b':
- Odd center: expand(0,0) → palindrome 'b', length 1
- Even center: expand(0,1) → not a palindrome ('ba')
- i = 1, character 'a':
- Odd center: expand(1,1) → palindrome 'a', length 1
- Even center: expand(1,2) → not a palindrome ('ab')
- i = 2, character 'b':
- Odd center: expand(2,2) → palindrome 'b', length 1
- Even center: expand(2,3) → palindrome 'ba', expands to 'bab', length 3
- Update start = 0, maxLength = 3
- i = 3, character 'a':
- Odd center: expand(3,3) → palindrome 'a', length 1
- Even center: expand(3,4) → not a palindrome ('ad')
- i = 4, character 'd':
- Odd center: expand(4,4) → palindrome 'd', length 1
- Even center: expand(4,5) → out of bounds
- Result: s.substring(0, 3) = "bab"
Hints
Hint 1
Hint 2
Hint 3
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize the expansion process around each center position and track the longest palindromic substring found.
Key visualization elements:
- current center
- expanding boundaries
- current longest palindrome
Implementation Notes
The 'Expand Around Center' approach is generally preferred due to its simplicity and O(1) space complexity, despite both approaches having the same time complexity. For very long strings, the DP approach might be faster in practice due to better cache locality.