#5
Longest Palindromic Substring
MediumTwo PointersStringDynamic ProgrammingHash MapArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Expand Around Center)★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n²)Space O(1)
Instead of checking all substrings, we can take advantage of the properties of palindromes. A palindrome mirrors around its center. Therefore, we can expand around each character (and between characters for even-length palindromes) to find the longest palindrome efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to store the longest palindrome found.
- 2Step 2: For each character in the string, treat it as the center of a potential palindrome.
- 3Step 3: Expand outwards while the characters on both sides are equal, updating the longest palindrome when a longer one is found.
solution.py28 lines
1# Full working Python code with comments
2
3def longest_palindrome(s):
4 if len(s) < 1:
5 return ""
6
7 start, end = 0, 0
8
9 for i in range(len(s)):
10 len1 = expand_around_center(s, i, i) # Odd length
11 len2 = expand_around_center(s, i, i + 1) # Even length
12 max_len = max(len1, len2)
13
14 if max_len > end - start:
15 start = i - (max_len - 1) // 2
16 end = i + max_len // 2
17
18 return s[start:end + 1]
19
20
21def expand_around_center(s, left, right):
22 while left >= 0 and right < len(s) and s[left] == s[right]:
23 left -= 1
24 right += 1
25 return right - left - 1
26
27# Example usage
28print(longest_palindrome('babad')) # Output: 'bab' or 'aba'ℹ
Complexity note: The time complexity is O(n²) because we may expand around each character and in the worst case, we may expand for every character in the string. However, we are not generating substrings explicitly, which saves space.
- 1Recognizing that palindromes can be expanded around their center helps reduce unnecessary checks.
- 2Understanding the difference between odd and even length palindromes is crucial for an optimal solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.