Longest Palindromic Substring - Problem
Find the longest palindromic substring in a given string. A palindrome is a word, phrase, or sequence that reads the same backward as forward, like
Given a string
Example: In the string
"racecar" or "madam".Given a string
s, you need to return the longest contiguous substring that forms a palindrome. If there are multiple palindromes of the same maximum length, return any one of them.Example: In the string
"babad", both "bab" and "aba" are valid answers since they're both palindromes of length 3. Input & Output
example_1.py — Basic Case
$
Input:
s = "babad"
›
Output:
"bab"
💡 Note:
Both "bab" and "aba" are valid answers as they are both palindromes of length 3. The algorithm returns "bab" as it's found first.
example_2.py — Even Length Palindrome
$
Input:
s = "cbbd"
›
Output:
"bb"
💡 Note:
"bb" is the longest palindromic substring. This demonstrates finding palindromes with even length (center between two characters).
example_3.py — Single Character
$
Input:
s = "a"
›
Output:
"a"
💡 Note:
A single character is always a palindrome, so the entire string is returned.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Centers
Every palindrome has a center - either on a character (odd length) or between characters (even length)
2
Expand Symmetrically
From each center, expand outward while characters match on both sides
3
Track Maximum
Keep track of the longest palindrome found during the expansion process
Key Takeaway
🎯 Key Insight: Every palindrome expands symmetrically from its center. By checking all possible centers and expanding outward, we can find the longest palindrome in O(n²) time.
Time & Space Complexity
Time Complexity
O(n²)
O(n) centers to check × O(n) expansion in worst case
⚠ Quadratic Growth
Space Complexity
O(1)
Only using a few variables to track the longest palindrome
✓ Linear Space
Constraints
- 1 ≤ s.length ≤ 1000
- s consists of only lowercase English letters
- Note: If there are multiple palindromes of the same maximum length, return any one of them
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code