Palindromic Substrings — LeetCode 647 Python Solution
- Problem
- #647
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward.
Example
- Input
- s = "abc"
- Output
- 3
- Explanation
- Three palindromic strings: "a", "b", "c".
Python solution
class Solution:
def countSubstrings(self, s: str) -> int:
ans, n = 0, len(s)
for k in range(n * 2 - 1):
i, j = k // 2, (k + 1) // 2
while ~i and j < n and s[i] == s[j]:
ans += 1
i, j = i - 1, j + 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 647. Palindromic Substrings 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 and NeetCode 150.
Frequently asked questions
- How hard is LeetCode 647. Palindromic Substrings?
- LeetCode 647. Palindromic Substrings is rated Medium on LeetCode.
- What is the time complexity of LeetCode 647. Palindromic Substrings?
- The Python solution on this page runs in O(n) (after optional sort O(n log n)).
- What is the space complexity of LeetCode 647. Palindromic Substrings?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 647. Palindromic Substrings cover?
- LeetCode 647. Palindromic Substrings is tagged Two Pointers, String and Dynamic Programming on LeetCode.