Longest Palindromic Substring - Problem

Given a string s, return the longest palindromic substring in s.

A palindrome is a string that reads the same forward and backward. For example, "racecar" and "aba" are palindromes.

If there are multiple palindromic substrings of the same maximum length, return any one of them.

Input & Output

Example 1 — Basic Case
$ Input: s = "babad"
Output: "bab"
💡 Note: Both "bab" and "aba" are valid palindromes of length 3. Either can be returned as they are both the longest.
Example 2 — Even Length Palindrome
$ Input: s = "cbbd"
Output: "bb"
💡 Note: The longest palindromic substring is "bb" with length 2. Single characters are also palindromes but shorter.
Example 3 — Single Character
$ Input: s = "a"
Output: "a"
💡 Note: A single character is always a palindrome, so return the entire string.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consist of only digits and English letters

Visualization

Tap to expand
Longest Palindromic Substring INPUT String s = "babad" b 0 a 1 b 2 a 3 d 4 Expand Around Center b a b expand Input: s = "babad" ALGORITHM STEPS 1 Iterate each index Treat as potential center 2 Expand outward Check odd & even length 3 Compare chars While s[L] == s[R], expand 4 Track longest Update max if longer Center Expansion Process i=0: "b" len=1 i=1: "bab" len=3 i=2: "bab" len=3 (max) i=3: "aba" len=3 i=4: "d" len=1 FINAL RESULT Longest Palindrome Found: b a b Verification: b - a - b b - a - b Forward = Backward OK - Valid Palindrome! Output: "bab" Length: 3 (or "aba" - both valid) Key Insight: The "Expand Around Center" approach treats each character (and gap between chars) as potential palindrome centers. For each center, expand outward while characters match. This achieves O(n^2) time and O(1) space - optimal for interviews. Manacher's algorithm can solve in O(n) but is complex. TutorialsPoint - Longest Palindromic Substring | Expand Around Center Approach
Asked in
Amazon 45 Microsoft 38 Google 32 Apple 25
125.0K Views
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