Data Structures & Algorithms Dynamic Programming — 2D
💡
Exercise 133

Longest Palindromic Substr 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Find the longest palindromic substring. The expand-around-center approach is elegant and uses O(1) space.

# For each center (and between chars): # Expand outward while chars match # Track the longest palindrome found # O(n²) time, O(1) space

Each character is a center for odd-length palindromes. Each pair of adjacent chars is a center for even-length palindromes.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Find the longest palindromic substring of 'babad'. Print its length.
Helper: expand(l, r) while l>=0 and r<n and s[l]==s[r]. Try both odd and even centers.
🧪 Test Cases
Input
len(longestPalindrome('babad'))
Expected
3
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.