Longest Palindromic Substring — LeetCode 5 Python Solution
MediumTwo PointersStringDynamic Programming
- Problem
- #5
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s, return the longest palindromic substring in s.
Example
- Input
- s = "babad"
- Output
- "bab"
- Explanation
- "aba" is also a valid answer.
Python solution
Python
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
f = [[True] * n for _ in range(n)]
k, mx = 0, 1
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
f[i][j] = False
if s[i] == s[j]:
f[i][j] = f[i + 1][j - 1]
if f[i][j] and mx < j - i + 1:
k, mx = i, j - i + 1
return s[k : k + mx]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n^2) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 5. Longest Palindromic Substring is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 5. Longest Palindromic Substring?
- LeetCode 5. Longest Palindromic Substring is rated Medium on LeetCode.
- What is the time complexity of LeetCode 5. Longest Palindromic Substring?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 5. Longest Palindromic Substring?
- The Python solution on this page uses O(n^2) auxiliary space.
- What topics does LeetCode 5. Longest Palindromic Substring cover?
- LeetCode 5. Longest Palindromic Substring is tagged Two Pointers, String and Dynamic Programming on LeetCode.