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
Palindrome Detection: Center Expansion MethodracecarCENTERStep 1: c==c โœ“ โ†’ Step 2: a==a โœ“ โ†’ Step 3: r==r โœ“ โ†’ Palindrome: "racecar"๐ŸŽฏ Key Insight: Palindromes grow symmetrically from their center
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.
Asked in
Amazon 42 Microsoft 38 Google 35 Facebook 28 Apple 22
987.0K Views
Very High Frequency
~15 min Avg. Time
18.5K 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