Palindromic Substrings solution explained

Palindromic Substrings asks how many contiguous slices of a string are palindromes, counting slices at different positions separately even when they spell the same thing. Loop over the 2n - 1 centers and add one for every step an expansion survives, which gives an O(n²) time, O(1) space count. An interval DP table, where a slice is a palindrome if its ends match and its inside is one, also runs in O(n²) and is the better base for follow-ups like palindrome partitioning.

By Published 7 min read

The task, restated

Take a string and look at every slice of it: every choice of a start and an end with the start not after the end. Count how many of those slices are palindromes. Two slices that spell the same word but sit at different positions are counted twice. Every single character is a palindrome on its own, so the answer is always at least the length of the string.

Examples made up for this page
InputCountThe palindromic slices
noon6n, o, o, n, oo, noon
level7l, e, v, e, l, eve, level
kiwi5k, i, w, i, iwi
mmmm10four of length 1, three of length 2, two of length 3, one of length 4
z1z
Examples made up for this page. Scroll sideways on a small screen.

The question to ask first is whether duplicates count once or by position. The usual version counts by position, which is what the examples above do. Counting distinct palindromes is a harder follow-up, covered below.

What the interviewer is checking

Interviewers often pair this problem with Longest Palindromic Substring, sometimes as a direct follow-up. They want to see whether you can turn a search into a count without changing the core idea, and whether you can define a DP state over intervals. A strong answer shows both ways and says when you would pick each: the center loop for the bare count, the table when later questions need to know which slices are palindromes.

Brute force: test every slice

Two loops pick a start and an end, and a third check compares the slice with its reverse. That is O(n²) slices times O(n) per check, O(n³) overall. Fine for a few dozen characters, and a solid reference for random testing.

def mirror_count_slow(word):
    total = 0
    for i in range(len(word)):
        for j in range(i + 1, len(word) + 1):
            chunk = word[i:j]
            total += chunk == chunk[::-1]
    return total
Count by testing every slice, O(n³).

Interval DP: let short slices answer for long ones

Write pal[i][j] for whether the slice from i to j, both ends included, is a palindrome. A slice of length 1 always is. A slice of length 2 is when its two characters match. A longer slice is when its end characters match and pal[i + 1][j - 1] is true. Because the rule reads a slice that is two characters shorter, fill the table by increasing length, or by i from right to left with j from left to right. Every true cell is one palindrome, so count them as you go.

def mirror_count_table(word):
    n = len(word)
    pal = [[False] * n for _ in range(n)]
    total = 0
    for i in range(n - 1, -1, -1):
        for j in range(i, n):
            if word[i] == word[j] and (j - i < 2 or pal[i + 1][j - 1]):
                pal[i][j] = True
                total += 1
    return total
Python: interval table, O(n²) time and O(n²) space.
True cells of the table for level, by slice
LengthPalindromic slices (start..end)Running count
10..0 l, 1..1 e, 2..2 v, 3..3 e, 4..4 l5
2none: le, ev, ve and el all have different ends5
31..3 eve (ends e and e, middle v is a palindrome)6
4none6
50..4 level (ends l and l, inside eve is true)7
True cells of the table for level, by slice. Scroll sideways on a small screen.

The condition j - i < 2 covers slices of length 1 and 2, whose inside is empty or nonexistent, so the code never reads a cell below the diagonal.

Optimal space: one loop over centers

Every palindrome has exactly one center, either a character or the gap between two characters. Number the centers 0 to 2n - 2: even numbers are characters, odd numbers are gaps. For center c, the two pointers start at c // 2 and c // 2 + c % 2. Each time the characters under the pointers match, you have found one more palindrome; widen and try again. No palindrome is counted twice, because each is reached from its own center only.

def mirror_count(word):
    n = len(word)
    total = 0
    for center in range(2 * n - 1):
        left = center // 2
        right = left + center % 2
        while left >= 0 and right < n and word[left] == word[right]:
            total += 1
            left -= 1
            right += 1
    return total
Python: 2n - 1 centers in one loop, O(n²) time, O(1) space.
function mirrorCount(word) {
  const n = word.length;
  let total = 0;
  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 && word[left] === word[right]) {
      total++;
      left--;
      right++;
    }
  }
  return total;
}
JavaScript: the same center loop.

For an empty string, 2n - 1 is -1, the loop never runs, and the count is 0. That is correct, but say it out loud since it falls out of the arithmetic rather than a check.

Follow-ups you may hear

  • Count distinct palindromes only. Collect slices in a set as you expand, which costs extra memory for the strings, or hash slices. For long inputs, a palindromic tree (eertree) tracks distinct palindromes in linear time.
  • Fewest cuts so every piece is a palindrome. Build the interval table first, then a one-dimensional DP over prefixes. This is where the table pays for itself.
  • Return the longest one instead of a count. Same centers, keep the widest instead of adding; see the related page below.
  • Count palindromic subsequences, not substrings. A different interval DP, because subsequences may skip characters.

Time and space

Cost for a string of length n
VersionTimeExtra space
Every slice with a reverse checkO(n³)O(n) per slice copy
Interval DP tableO(n²)O(n²)
Loop over 2n - 1 centersO(n²) worst caseO(1)
Manacher radii, summedO(n)O(n)
Cost for a string of length n. Scroll sideways on a small screen.

Since the count itself can be about n² / 2, as in mmmm, any method that touches each palindrome once cannot beat O(n²) in the worst case. Manacher avoids that by adding up radii instead of visiting each palindrome.

Edge cases

  • Empty string: 0.
  • One character: 1.
  • No repeated neighbors and no mirrored triples: exactly n.
  • One letter repeated n times: n(n + 1) / 2.
  • Mixed case or punctuation: ask whether to normalize. The counts above compare characters exactly.

Mistakes to avoid

  • Only using odd centers, which drops oo in noon and every even palindrome.
  • Filling the DP table row by row from the top, so pal[i + 1][j - 1] has not been computed yet.
  • Counting distinct strings when the question counts positions, or the reverse.
  • Running the longest-palindrome expansion and returning its length instead of a count.
  • Using the O(n²) table when only the count is needed and memory is tight.

How to explain it out loud

Fictional example

Two approaches, one sentence each
Candidate
Each palindrome has one center, a letter or a gap, so I can loop over the 2n minus 1 centers and add one every time the expansion takes another matching step.
Candidate
That is quadratic time and constant memory. If you later want to know which slices are palindromes, I would switch to a table where a slice counts when its ends match and its inside counted.
Candidate
Quick check on noon: four letters, one oo from the middle gap, and noon itself from that same gap. Six, which matches.

Longest Palindromic Substring uses the same centers to find the widest palindrome rather than count them. Min Cost to Connect All Points leaves strings behind for a graph, where the work is again quadratic but for a different reason. House Robber is a gentler introduction to filling a DP table in the right order.

Where Natively fits

Counting problems are easy to get almost right, so checking your total against a second source helps. While you practice on Mac or Windows, Natively can read this problem from a screenshot, suggest both the center loop and the table with code, and transcribe your mock session for later review. That transcript is a quick way to see whether you clarified duplicates before writing code. Setup is described on the AI interview assistant page.

Questions people ask

How do you count palindromic substrings efficiently?

Loop over the 2n - 1 centers, letters and gaps, and expand outward while the two characters match, adding one for each successful step. Each palindrome is found once, from its own center, in O(n²) time and O(1) space.

What is the DP solution for Palindromic Substrings?

Let pal[i][j] be true when the slice from i to j is a palindrome: its ends match and either it is shorter than three characters or pal[i + 1][j - 1] is true. Fill it so shorter slices come first and count the true cells.

Do duplicate palindromes count more than once?

In the usual version, yes. Slices at different positions are counted separately, so noon has two single o's. Counting distinct palindromes is a separate follow-up.

What is the worst case for Palindromic Substrings?

A string of one repeated letter. Every slice is a palindrome, so there are n(n + 1) / 2 of them, and any method that visits each one takes quadratic time.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP