Palindromic Substrings — LeetCode 647 Python Solution

MediumTwo PointersStringDynamic Programming
Problem
#647
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview