Palindromic Substring Count

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

You are given a string s and need to determine how many non-empty contiguous slices of s form palindromes.

A slice s[i:j] (with 0 <= i < j <= len(s)) is considered palindromic when its sequence of characters is identical whether read left-to-right or right-to-left. Character matching is exact and case-sensitive ('A' is distinct from 'a').

Every valid index pair (i, j) counts toward the total independently, even if the same character sequence occurs at multiple positions within s. Return the total number of palindromic slices as an integer.

Examples

Example 1

Input: s = "wolf"
Output: 4

None of the multi-character slices match when reversed, leaving only the four single-character slices "w", "o", "l", and "f".

Example 2

Input: s = "zzzz"
Output: 10

Every non-empty contiguous slice is palindromic: four slices of length 1 ("z"), three of length 2 ("zz"), two of length 3 ("zzz"), and one of length 4 ("zzzz"), totaling 4 + 3 + 2 + 1 = 10.

Example 3

Input: s = "level"
Output: 7

The five single characters ("l", "e", "v", "e", "l") plus "eve" (s[1:4]) and "level" (s[0:5]) give 7 palindromic slices.

Example 4

Input: s = "redder"
Output: 9

Alongside the six length-1 slices ("r", "e", "d", "d", "e", "r"), expanding around the middle gap finds three even-length palindromes: "dd" (s[2:4]), "edde" (s[1:5]), and "redder" (s[0:6]).

Constraints

  • 0 <= len(s) <= 2000 (an empty string has 0 non-empty slices and returns 0).
  • s consists of ASCII characters, compared case-sensitively.
  • An O(n^2) time solution easily fits within time limits.

Step-by-step walkthrough

  1. Understand what we are counting

    We are given a string s and asked to count how many of its non-empty substrings are palindromes.

    • A substring is a contiguous slice s[i:j] (with 0 <= i < j <= len(s)), unlike a subsequence, which is allowed to skip characters.
    • A palindrome is a string whose characters match identically from front to back and back to front, such as "v", "dd", or "level".
    • We count occurrences by index pair, not unique strings. Whenever the same character pattern appears at multiple positions, every occurrence adds to the answer.
    • Comparisons are exact and case-sensitive, so 'A' and 'a' do not match.

    For example, in s = "zzzz", every non-empty contiguous slice is a palindrome, giving 10 in total:

    Index:   0   1   2   3
    Chars:   z   z   z   z
    
    Length 1:  s[0:1]="z", s[1:2]="z", s[2:3]="z", s[3:4]="z"  -> 4 palindromes
    Length 2:  s[0:2]="zz", s[1:3]="zz", s[2:4]="zz"           -> 3 palindromes
    Length 3:  s[0:3]="zzz", s[1:4]="zzz"                      -> 2 palindromes
    Length 4:  s[0:4]="zzzz"                                   -> 1 palindrome
    Total = 4 + 3 + 2 + 1 = 10
    
  2. Why checking every substring from scratch is slow

    The most direct approach tries every start index i and end index j, slices out s[i:j], and checks whether it equals its reverse:

    def brute_force_count(s: str) -> int:
        count = 0
        for i in range(len(s)):
            for j in range(i + 1, len(s) + 1):
                piece = s[i:j]
                if piece == piece[::-1]:
                    count += 1
        return count
    

    A string of length n has n * (n + 1) / 2 non-empty substrings. Slicing and reversing a substring of length k takes O(k) work, so the total time in the worst case is O(n^3). For n = 2000, n^3 is roughly 8 * 10^9 operations.

    Notice why this wastes work: after confirming that "edde" is a palindrome, testing "redder" slices the string again and re-compares "edde" from scratch instead of only checking the new outer pair 'r' and 'r'.

  3. Key idea: grow outward from every center

    Every palindrome is symmetric around its middle. If we already know the inner slice s[left + 1 .. right - 1] is a palindrome, then adding one character on each side forms a palindrome s[left .. right] if and only if s[left] == s[right].

    Instead of scanning from the outside in, we can start at a center and expand two pointers outward one step at a time:

    • Each step checks just two characters (s[left] == s[right]) in O(1) time.
    • Every match discovers one new palindrome.
    • The first mismatch stops the expansion for that center, because any wider substring around the same center would still contain that mismatched pair at the same distance from the middle.

    There are two kinds of centers in a string of length n:

    Odd-length palindrome ("eve")          Even-length palindrome ("edde")
    Center is ON a character (n centers)   Center is IN A GAP (n - 1 centers)
    
          center = 1                             gap after center = 1
              |                                          |
          e   v   e                              e   d   |   d   e
          ^       ^                              ^   ^       ^   ^
         left   right                               left   right
      step 1: s[1..1] = "v"                  step 1: s[1..2] = "dd"
      step 2: s[0..2] = "eve"                step 2: s[0..3] = "edde"
    

    Because every palindrome has a unique center (either a single middle character if its length is odd, or a middle gap if its length is even), expanding from all 2n - 1 centers finds every palindrome exactly once in O(n^2) total time and O(1) extra space.

  4. Write the center-expansion helper

    Let's write a helper count_from_center(s, left, right) that counts how many palindromes share a given starting center:

    • For an odd center at c, we call count_from_center(s, c, c). On the first iteration s[c] == s[c] is always true, which counts the 1-letter palindrome s[c], and then left and right step outward to c - 1 and c + 1.
    • For an even center after c, we call count_from_center(s, c, c + 1). On the first iteration it checks whether the two adjacent characters s[c] and s[c + 1] match.

    We check left >= 0 and right < len(s) before s[left] == s[right] so Python short-circuits as soon as either pointer steps past the ends of the string.

    def count_from_center(s: str, left: int, right: int) -> int:
        """Expand outward from s[left..right] and count every palindrome centered here."""
        palindromes_here = 0
    
        # s[left..right] is the current symmetric window around this center.
        # Check bounds first so s[left] and s[right] never raise IndexError.
        # As soon as s[left] != s[right], we stop: any wider window around this
        # same center would still contain that mismatched pair and cannot be a palindrome.
        while left >= 0 and right < len(s) and s[left] == s[right]:
            palindromes_here += 1
            left -= 1
            right += 1
    
        return palindromes_here
    
  5. Loop over all odd and even centers

    Now the main function simply loops center from 0 to len(s) - 1 and adds both the odd-length count and the even-length count.

    Notice we do not need a special case for the last index center = len(s) - 1: the even call passes right = len(s), which immediately fails right < len(s) in the helper and returns 0.

    def count_palindromic_substrings(s: str) -> int:
        # total_palindromes: running count of all palindromic substrings (by start/end index)
        total_palindromes = 0
    
        # Every palindrome is symmetric around either a single character or a gap between two.
        for center in range(len(s)):
            # Phase 1 — Odd-length palindromes (e.g., "v", "eve"):
            # both pointers begin on the middle character s[center].
            odd_count = count_from_center(s, center, center)
    
            # Phase 2 — Even-length palindromes (e.g., "dd", "edde"):
            # pointers begin on adjacent characters straddling the gap after s[center].
            # At the last index, right == len(s), so the helper's bounds check returns 0 safely.
            even_count = count_from_center(s, center, center + 1)
    
            total_palindromes += odd_count + even_count
    
        return total_palindromes
    
  6. Trace on Example 4 (`"redder"`)

    Let's trace s = "redder" (indices 0..5) step by step:

    s = "r e d d e r"
         0 1 2 3 4 5
    
    center = 0:
      odd  (0, 0): s[0]==s[0] ("r") -> +1; next (-1, 1) out of bounds           => odd_count = 1
      even (0, 1): s[0]='r' != s[1]='e' -> stop                                 => even_count = 0
    
    center = 1:
      odd  (1, 1): s[1]==s[1] ("e") -> +1; next (0, 2): 'r' != 'd' -> stop      => odd_count = 1
      even (1, 2): s[1]='e' != s[2]='d' -> stop                                 => even_count = 0
    
    center = 2:
      odd  (2, 2): s[2]==s[2] ("d") -> +1; next (1, 3): 'e' != 'd' -> stop      => odd_count = 1
      even (2, 3): s[2]==s[3] ("dd") -> +1;
                   next (1, 4): s[1]==s[4] ("edde") -> +1;
                   next (0, 5): s[0]==s[5] ("redder") -> +1;
                   next (-1, 6) out of bounds                                   => even_count = 3
    
    center = 3:
      odd  (3, 3): s[3]==s[3] ("d") -> +1; next (2, 4): 'd' != 'e' -> stop      => odd_count = 1
      even (3, 4): s[3]='d' != s[4]='e' -> stop                                 => even_count = 0
    
    center = 4:
      odd  (4, 4): s[4]==s[4] ("e") -> +1; next (3, 5): 'd' != 'r' -> stop      => odd_count = 1
      even (4, 5): s[4]='e' != s[5]='r' -> stop                                 => even_count = 0
    
    center = 5:
      odd  (5, 5): s[5]==s[5] ("r") -> +1; next (4, 6) out of bounds            => odd_count = 1
      even (5, 6): right=6 out of bounds -> stop                                => even_count = 0
    
    total_palindromes = 1 + 1 + 4 + 1 + 1 + 1 = 9
    Found: six single letters plus "dd" (2..3), "edde" (1..4), and "redder" (0..5).
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_from_center(s: str, left: int, right: int) -> int:
        """Expand outward from s[left..right] and count every palindrome centered here."""
        palindromes_here = 0
    
        # s[left..right] is the current symmetric window around this center.
        # Check bounds first so s[left] and s[right] never raise IndexError.
        # As soon as s[left] != s[right], we stop: any wider window around this
        # same center would still contain that mismatched pair and cannot be a palindrome.
        while left >= 0 and right < len(s) and s[left] == s[right]:
            palindromes_here += 1
            left -= 1
            right += 1
    
        return palindromes_here
    
    
    def count_palindromic_substrings(s: str) -> int:
        # total_palindromes: running count of all palindromic substrings (by start/end index)
        total_palindromes = 0
    
        # Every palindrome is symmetric around either a single character or a gap between two.
        for center in range(len(s)):
            # Phase 1 — Odd-length palindromes (e.g., "v", "eve"):
            # both pointers begin on the middle character s[center].
            odd_count = count_from_center(s, center, center)
    
            # Phase 2 — Even-length palindromes (e.g., "dd", "edde"):
            # pointers begin on adjacent characters straddling the gap after s[center].
            # At the last index, right == len(s), so the helper's bounds check returns 0 safely.
            even_count = count_from_center(s, center, center + 1)
    
            total_palindromes += odd_count + even_count
    
        return total_palindromes
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of folding a strip of paper in half at a crease. A palindrome (a string whose characters match identically left-to-right and right-to-left) is symmetric around its middle, so once the inner part of a substring (a contiguous slice of characters) already matches up, you only need to look one step further out on the left and right to see whether the wider slice is a palindrome too.

The naive approach generates all n * (n + 1) / 2 substrings and reverses each one from scratch, which takes O(n^3) time in the worst case. It is slow because it throws away work it just did: after confirming that "edde" is a palindrome, it re-checks all four of those inner letters when testing "redder". By instead starting at each possible middle — called two-pointer center expansion (placing left and right pointers at a center and stepping them outward in lockstep while characters match) — each new palindrome is verified with a single O(1) character comparison.

Walk through s = "level" (indices 0 to 4), checking both character centers (for odd-length palindromes) and gap centers between neighbors (for even-length palindromes):

  • Center 0 ('l'): odd gives "l" (+1); gap 0|1 compares 'l' vs 'e', mismatch (+0).
  • Center 1 ('e'): odd gives "e" (+1), then 'l' vs 'v' stops; gap 1|2 compares 'e' vs 'v', mismatch (+0).
  • Center 2 ('v'): odd gives "v" (+1), expands to 'e' == 'e' ("eve", +1), and expands to 'l' == 'l' ("level", +1); gap 2|3 compares 'v' vs 'e', mismatch (+0).
  • Center 3 ('e'): odd gives "e" (+1); gap 3|4 compares 'e' vs 'l', mismatch (+0).
  • Center 4 ('l'): odd gives "l" (+1); gap 4|5 is out of bounds (+0).

Adding those up gives 1 + 1 + 3 + 1 + 1 = 7 palindromic substrings.

Complexity

  • Time: O(n^2) in the worst case, where n = len(s). We try 2n starting pointer pairs (n character centers and n gap centers, with the last gap stopping immediately), and each pointer pair expands outward at most n / 2 times doing an O(1) comparison per step. When all characters are distinct (such as "wolf"), every expansion stops after at most one step in O(n) time; when all characters match (such as "z" * 2000), every substring is palindromic and we perform n * (n + 1) / 2 comparisons.
  • Space: O(1) auxiliary space, because we never slice substrings or allocate a table — we only keep a few integer indices (center, left, right) and integer counters.

Edge cases

  • Single character ("z"): Odd expansion at index 0 counts "z", even expansion goes out of bounds immediately, returning 1.
  • Empty string (""): The loop over range(0) does not run and returns 0.
  • All identical characters ("zzzz" or "a" * 2000): Every contiguous slice is a palindrome, yielding n * (n + 1) / 2 (10 for "zzzz", 2,001,000 for n = 2000).
  • Even-length palindromes ("dd", "redder"): Have no middle character, so they are only found by the count_from_center(s, center, center + 1) gap checks.
  • Duplicate palindrome text at different indices ("abab"): "aba" at 0..2 and "bab" at 1..3, plus the four 1-letter substrings ("a" twice and "b" twice), all count separately for 6.
  • Case sensitivity ("Aa"): 'A' and 'a' have different character codes, so "Aa" returns 2, not 3.

Common mistakes

  • Forgetting even-length centers: Expanding only from (center, center) misses every even-length palindrome and returns 6 instead of 9 on "redder".
  • Deduplicating with a set: Putting palindrome strings into a set counts unique texts (4 for "zzzz") rather than every substring position (10).
  • Checking characters before array bounds: Writing while s[left] == s[right] and left >= 0 ... raises IndexError when right == len(s) or in Python wraps s[-1] around to the last character of the string! Always check left >= 0 and right < len(s) first.
  • Continuing past a mismatch: Using an if inside a fixed loop instead of stopping the while loop on the first mismatch falsely counts strings like "abca" just because the outer 'a's match.
  • Allocating an n x n table unnecessarily: Solving this with a 2D boolean table uses O(n^2) memory (4 million booleans for n = 2000) when center expansion achieves the exact same O(n^2) time in O(1) memory.

Alternative approaches

  • 2D Dynamic Programming: Dynamic programming (DP) solves a problem by storing answers to smaller subproblems in a table so each subproblem is computed once. Define is_pal[i][j] as whether s[i..j] is a palindrome, filled by increasing substring length using s[i] == s[j] and (j - i <= 2 or is_pal[i + 1][j - 1]). This also runs in O(n^2) time, but uses O(n^2) space (or O(n) if rolled across two rows).
  • Manacher's algorithm: Manacher's algorithm is a linear-time palindrome finder that reuses mirror symmetry inside the rightmost palindrome seen so far to skip redundant comparisons. Once you know the maximum palindrome radius r at each odd and even center, that center contributes r palindromes, summing to the answer in O(n) time and O(n) space.

Follow-up questions

  • How could you reduce the worst-case time complexity from O(n^2) down to O(n)? Use Manacher's algorithm. Inserting a sentinel separator like '#' between adjacent characters converts both odd and even palindromes into odd-length palindromes, and tracking the palindrome with the farthest-right boundary lets each new center seed its radius from its mirror center before expanding. Because that right boundary advances at most 2n + 1 steps across the entire string, total runtime drops to O(n) using O(n) auxiliary memory.
  • What changes if we only want the number of unique palindromic strings rather than counting every index pair? For n <= 2000, keep the center-expansion loop, compute a rolling hash (a numeric fingerprint of s[left..right] obtainable in O(1) time from precomputed prefix hashes) modulo two large primes to avoid collisions, and insert each (length, hash1, hash2) tuple into a set in O(n^2) time — avoiding s[left:right + 1] string slicing, which would degrade worst-case time back to O(n^3). Optimal O(n) time is also achievable with an eertree (palindromic tree), because a string of length n contains at most n distinct non-empty palindromes.
  • How would you adapt center expansion to return the longest palindromic slice instead of the total count? Keep the exact same center-expansion loop, but instead of summing counts, track (best_start, best_len) whenever a matched window right - left + 1 exceeds best_len, then slice s[best_start : best_start + best_len] once at the end. That runs in O(n^2) time and O(1) working memory.

Follow-up questions

Similar questions

More Reevo interview questions

All 3 Reevo questions →