Longest Palindromic Substring - Problem
Given a string s, return the longest palindromic substring in s.
A palindrome is a string that reads the same backward as forward. For example, "racecar" and "aba" are palindromes.
If there are multiple palindromes of the same maximum length, you may return any of them.
Input & Output
Example 1 โ Basic Case
$
Input:
"s = \"babad\""
โบ
Output:
"\"bab\""
๐ก Note:
"bab" is a palindrome. Note that "aba" is also a valid answer since it's also the longest palindromic substring.
Example 2 โ Even Length Palindrome
$
Input:
s = "cbbd"
โบ
Output:
"bb"
๐ก Note:
"bb" is the longest palindromic substring in this case.
Example 3 โ Single Character
$
Input:
s = "a"
โบ
Output:
"a"
๐ก Note:
A single character is always a palindrome.
Constraints
- 1 โค s.length โค 1000
- s consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Identify Center
Every palindrome has a center - either a character or between characters
2
Expand Symmetrically
Move outward from center while left and right characters match
3
Track Maximum
Remember the longest palindrome found during expansion
Key Takeaway
๐ฏ Key Insight: Every palindrome has a center point from which it expands symmetrically. By checking each position as a potential center and expanding outward, we can efficiently find the longest palindrome in O(nยฒ) time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code