Palindromic Substrings
A medium Strings interview guide. Task statement, worked examples, intuition, and step-by-step solutions.
- Topic
- Strings
- Sheets
- 2
- Core for
- 14 roles
The problem
Given a string, count the total number of palindromic substrings.
Example 1
- Input
- "abc"
- Output
- 3
Example 2
- Input
- "aaa"
- Output
- 6
Example 3
- Input
- "abba"
- Output
- 6
Constraints
- 1 <= s.length <= 1000
- s consists of lowercase English letters
How to think about it
Updated 2026-09-29Every palindrome mirrors around its middle. A string of length n has exactly 2n - 1 possible centers: n single characters for odd lengths and n - 1 adjacent character gaps for even lengths. Growing outward symmetrically from each center counts every valid palindrome without ever re-evaluating inner substrings.
Approaches, worst first
Inspect all substrings
time O(n^3) · space O(1)
Extract every substring pair (i, j) and verify whether it reads identically forward and backward with a two-pointer check. It inspects O(n^2) substrings and spends O(n) validating each one independently.
Table dynamic programming
time O(n^2) · space O(n^2)
dp[i][j] marks whether s[i..j] is a palindrome, depending on s[i] == s[j] and dp[i+1][j-1]. Fills substrings in increasing order of length, eliminating redundant inner checks at the expense of an explicit 2D boolean grid.
Expand around centersWrite this one
time O(n^2) · space O(1)
Treat each index as an odd center (i, i) and each adjacent pair as an even center (i, i+1). Step two pointers outward as long as matching characters continue. Each successful expansion directly increments the running total while using zero auxiliary heap memory.
Where people lose marks · 3
- Neglecting even-length palindromes like 'abba' by only treating single characters as centers.
- Missing the baseline single-character palindromes. When s has length n, the answer is always at least n.
- Index out-of-bounds when stepping pointers outward past index 0 or index n - 1 before testing equality.
Full solution
Expand around each of the 2n - 1 centers: O(n^2) time with O(1) space, and one loop covers both odd and even lengths so the 'abba' case is never forgotten.
Python
def count_substrings(s: str) -> int:
n = len(s)
total = 0
# 2n - 1 centers: (i, i) for odd lengths, (i, i + 1) for even lengths
for center in range(2 * n - 1):
left = center // 2
right = left + center % 2
while left >= 0 and right < n and s[left] == s[right]:
total += 1
left -= 1
right += 1
return total
JavaScript
function countSubstrings(s) {
const n = s.length;
let total = 0;
// 2n - 1 centers: (i, i) for odd lengths, (i, i + 1) for even lengths
for (let center = 0; center < 2 * n - 1; center++) {
let left = Math.floor(center / 2);
let right = left + (center % 2);
while (left >= 0 && right < n && s[left] === s[right]) {
total++;
left--;
right++;
}
}
return total;
}
The theory behind it
Strings — the ground this problem stands on. All Strings problems
What Strings is
A string is an ordered necklace of text characters, like letters printed along a ribbon of paper. Each character sits at an exact numeric slot, holding a glyph such as a letter, punctuation mark, or digit. In many programming languages, ribbons cannot be edited after creation, meaning changing a single character requires pressing an entirely new ribbon from scratch.
When to reach for it
Reach for string techniques when inputs consist of words, DNA sequences, serialized data formats, or sentences. Clues include questions testing palindromes, anagram matches, substring patterns, parenthesis balancing, or character frequency counts. Whenever an algorithm asks to transform capitalization, parse structured tokens, or compute edits between two phrases, string representations are the core subject.
How the pattern works
Think of characters as small integer codes ranging across standard character sets. Frequency tables with fixed sizes often replace heavy hash maps when tallying occurrences. For search tasks, maintain rolling state using character indices or sliding borders. When building output text through repeated appends, accumulate pieces inside a mutable list or string builder rather than concatenating strings directly, avoiding quadratic copy overhead.
More Strings problems
Target Roles
Core requirement for 14 roles:
Track in your role's order
Pick your target role and all 370 problems resequence to what that interview actually asks.
Start freeProblem set and role mapping as of .