← DSA
MEDIUM

Palindromic Substrings

PracticeNeetCode ↗LeetCode ↗

Given a string s, return the number of palindromic substrings it contains — every occurrence counts separately, even if the text of two substrings is identical.

Example

Input s = "aaa"
Output 6

Key Pointers

Step-by-Step Analysis

  1. Initialize a counter to 0.
  2. Write a helper that expands from (left, right) while the characters match, incrementing the counter once per successful match before moving further out.
  3. For each index i, call the helper for the odd center (i, i) and the even center (i, i+1).
  4. Return the total count after checking every center.

Complexity

Time: O(n²) — Space: O(1)

Code

def countSubstrings(s: str) -> int:
    count = 0

    def expand(left: int, right: int) -> None:
        nonlocal count
        while left >= 0 and right < len(s) and s[left] == s[right]:
            count += 1
            left -= 1
            right += 1

    for i in range(len(s)):
        expand(i, i)
        expand(i, i + 1)

    return count

Code Explanation

How the solution above works, piece by piece.

  1. Same centre-expansion idea as Longest Palindromic Substring, but count every palindrome instead of keeping the longest.
  2. Each index is an odd centre (i, i) and, with its right neighbour, an even centre (i, i + 1).
  3. Every successful step of the expansion is one more palindromic substring, so count += 1 inside the loop.
  4. Expansion stops at the first mismatch: anything wider around that centre can't be a palindrome either.
  5. O(n²) time, O(1) space.

Visual Walkthrough

Running it on s = "aaa":

tracea0a1a2centre 0"a" count 1aaacentre 0|1"aa" count 2aaacentre 1"a" count 3aaacentre 1"aaa" count 4aaacentre 1|2"aa" count 5aaacentre 2"a" count 6
Each row is one palindrome counted by the loop: three single letters, two "aa" and one "aaa" = 6.
palindrome

Video Explanation

NeetCode — Palindromic Substrings, LeetCode 647