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 "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
Center Expansion VisualizationString: "racecar"racecarCENTERc = c ✓c = c ✓a = a ✓a = a ✓r = r ✓r = r ✓Expansion Steps:1. Start at center 'e'2. Expand: 'cec' ✓3. Expand: 'aceca' ✓4. Expand: 'racecar' ✓Result: Entire string!Length: 7 characters
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

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track the longest palindrome

n
2n
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
Asked in
Amazon 85 Microsoft 72 Google 68 Meta 54
89.4K Views
Very High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen