Link: 5. Longest Palindromic Substring - Medium
Track: NeetCode150
Question
Restate the problem
Given a string of lowercase English letters.
Return the longest contiguous substring that is palindrome.
- palindromic: it reads the same forwards and backwards. mirrors around its center.
- Method 1: Brute Force, check every possible substring. take O()
- Method 2: Expand around the center
Method: Expand around the center
Approach
Every palindrome can be expanded from its center.
- Iterate through each index, consider two cases: odd, even
- Use two pointers to expand outward while characters match
- After expansion stops, restore two pointers to get validate palindrome range.
- Track the maximum length and record the substring
Complexity
- Time Complexity: O()
- Space Complexity: O(1) (excluding output)
Edge Case
- Empty string → return
""
Code
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
max_length = 0
res = ""
def expand(left, right):
while 0 <= left and right < n and s[left] == s[right]:
left -= 1
right += 1
return (left + 1, right - 1)
for idx in range(n):
even_left, even_right = expand(idx, idx + 1)
odd_left, odd_right = expand(idx, idx)
if max_length < even_right - even_left + 1:
max_length = even_right - even_left + 1
res = s[even_left: even_right + 1]
if max_length < odd_right - odd_left + 1:
max_length = odd_right - odd_left + 1
res = s[odd_left: odd_right + 1]
return res
History
Jan-25-2026 Solved w bug
Jan-22-2026 Solved w bug
returnindentation
Jan-22-2026 Solved w bug
- Wrote the
odd_pointerupdate incorrectly.
Jan-19-2026 Solved w bug, forget to restore pointer