MediumNo. 0005
Longest Palindromic Substring — LeetCode 5 Python Solution
- Pattern
- Two Pointers
- Topics
- Two Pointers, String, Dynamic Programming
- On study lists
- Blind 75, NeetCode 150, Grind 75 and Top Interview 150
- 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
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
- Time
- O(n2)
- Space · auxiliary
- O(n2)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0392 | Is Subsequence | Easy |
| 0647 | Palindromic Substrings | Medium |
| 0838 | Push Dominoes | Medium |
| 2911 | Minimum Changes to Make K Semi-palindromes | Hard |
| 0028 | Find the Index of the First Occurrence in a String | Easy |
| 0125 | Valid Palindrome | Easy |
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(n2).
- What is the space complexity of LeetCode 5. Longest Palindromic Substring?
The Python solution on this page uses O(n2) 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.