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 has0non-empty slices and returns0).sconsists of ASCII characters, compared case-sensitively.- An
O(n^2)time solution easily fits within time limits.
Step-by-step walkthrough
Understand what we are counting
We are given a string
sand asked to count how many of its non-empty substrings are palindromes.- A substring is a contiguous slice
s[i:j](with0 <= 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, giving10in 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- A substring is a contiguous slice
Why checking every substring from scratch is slow
The most direct approach tries every start index
iand end indexj, slices outs[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 countA string of length
nhasn * (n + 1) / 2non-empty substrings. Slicing and reversing a substring of lengthktakesO(k)work, so the total time in the worst case isO(n^3). Forn = 2000,n^3is roughly8 * 10^9operations.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'.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 palindromes[left .. right]if and only ifs[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]) inO(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 - 1centers finds every palindrome exactly once inO(n^2)total time andO(1)extra space.- Each step checks just two characters (
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 callcount_from_center(s, c, c). On the first iterations[c] == s[c]is always true, which counts the 1-letter palindromes[c], and thenleftandrightstep outward toc - 1andc + 1. - For an even center after
c, we callcount_from_center(s, c, c + 1). On the first iteration it checks whether the two adjacent characterss[c]ands[c + 1]match.
We check
left >= 0 and right < len(s)befores[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- For an odd center at
Loop over all odd and even centers
Now the main function simply loops
centerfrom0tolen(s) - 1and 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 passesright = len(s), which immediately failsright < len(s)in the helper and returns0.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_palindromesTrace on Example 4 (`"redder"`)
Let's trace
s = "redder"(indices0..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).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); gap0|1compares'l'vs'e', mismatch (+0). - Center
1('e'): odd gives"e"(+1), then'l'vs'v'stops; gap1|2compares'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); gap2|3compares'v'vs'e', mismatch (+0). - Center
3('e'): odd gives"e"(+1); gap3|4compares'e'vs'l', mismatch (+0). - Center
4('l'): odd gives"l"(+1); gap4|5is 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, wheren = len(s). We try2nstarting pointer pairs (ncharacter centers andngap centers, with the last gap stopping immediately), and each pointer pair expands outward at mostn / 2times doing anO(1)comparison per step. When all characters are distinct (such as"wolf"), every expansion stops after at most one step inO(n)time; when all characters match (such as"z" * 2000), every substring is palindromic and we performn * (n + 1) / 2comparisons. - 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 index0counts"z", even expansion goes out of bounds immediately, returning1. - Empty string (
""): The loop overrange(0)does not run and returns0. - All identical characters (
"zzzz"or"a" * 2000): Every contiguous slice is a palindrome, yieldingn * (n + 1) / 2(10for"zzzz",2,001,000forn = 2000). - Even-length palindromes (
"dd","redder"): Have no middle character, so they are only found by thecount_from_center(s, center, center + 1)gap checks. - Duplicate palindrome text at different indices (
"abab"):"aba"at0..2and"bab"at1..3, plus the four 1-letter substrings ("a"twice and"b"twice), all count separately for6. - Case sensitivity (
"Aa"):'A'and'a'have different character codes, so"Aa"returns2, not3.
Common mistakes
- Forgetting even-length centers: Expanding only from
(center, center)misses every even-length palindrome and returns6instead of9on"redder". - Deduplicating with a
set: Putting palindrome strings into a set counts unique texts (4for"zzzz") rather than every substring position (10). - Checking characters before array bounds: Writing
while s[left] == s[right] and left >= 0 ...raisesIndexErrorwhenright == len(s)or in Python wrapss[-1]around to the last character of the string! Always checkleft >= 0 and right < len(s)first. - Continuing past a mismatch: Using an
ifinside a fixed loop instead of stopping thewhileloop on the first mismatch falsely counts strings like"abca"just because the outer'a's match. - Allocating an
n x ntable unnecessarily: Solving this with a 2D boolean table usesO(n^2)memory (4 million booleans forn = 2000) when center expansion achieves the exact sameO(n^2)time inO(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 whethers[i..j]is a palindrome, filled by increasing substring length usings[i] == s[j] and (j - i <= 2 or is_pal[i + 1][j - 1]). This also runs inO(n^2)time, but usesO(n^2)space (orO(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
rat each odd and even center, that center contributesrpalindromes, summing to the answer inO(n)time andO(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 most2n + 1steps across the entire string, total runtime drops toO(n)usingO(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 ofs[left..right]obtainable inO(1)time from precomputed prefix hashes) modulo two large primes to avoid collisions, and insert each(length, hash1, hash2)tuple into a set inO(n^2)time — avoidings[left:right + 1]string slicing, which would degrade worst-case time back toO(n^3). OptimalO(n)time is also achievable with an eertree (palindromic tree), because a string of lengthncontains at mostndistinct 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 windowright - left + 1exceedsbest_len, then slices[best_start : best_start + best_len]once at the end. That runs inO(n^2)time andO(1)working memory.
Follow-up questions
- How could you reduce the worst-case time complexity from O(n^2) down to O(n)?
- What changes if we only want the number of unique palindromic strings rather than counting every index pair?
- How would you adapt center expansion to return the longest palindromic slice instead of the total count?
Similar questions
- Fast Word Membership Lookup at Scale
- Top Teams from a Paginated HTTP Endpoint
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance