Scrivio Interview library
Strings and triesArrays and stringsReported 18 times · 15 min read · updated 14 November 2026

How many substrings of a given string are palindromes? Count them.

1What we are counting, with a small mirror on the page

Imagine writing a word on paper and standing a small mirror upright across the middle of it. If the half you see reflected matches the other half exactly, the word reads the same forwards and backwards, and we call it a palindrome. For racecar the mirror stands on the letter e, in the very middle. For abba it stands in the gap between the two b's. Keep that mirror in mind; the whole solution is about where we can stand it.

A substring is a run of characters that sit side by side in the string, with nothing skipped. The question asks how many substrings of a given string are palindromes. Substrings at different positions count separately, even when they hold the same letters, and every single character counts, because one letter always matches itself in the mirror.

Let us work three small examples by hand. In abc, each single letter is a palindrome and nothing longer is, so the answer is 3. In aaa there are three single a's, two copies of aa, at positions 0 to 1 and 1 to 2, and one aaa, so the answer is 6. In abba there are four single letters, bb and abba, which again makes 6. We will use abba for the whole article.

PictureThe six palindromes inside abba

Each row is the string abba with one palindromic substring marked: four single letters, then bb, then abba.

  1. abbaabbaabbaabbaabbaabba

    1Reading the rows from the top, the palindromes are a, b, b, a, bb and abba. Two equal letters at different places count separately, so the answer is 6.

What to assume

Do equal substrings at different positions count separately?
Yes, we count positions, not distinct strings.
Do single characters count?
Yes.
Is the comparison exact, so that A and a differ, and do spaces count?
We assume an exact comparison of every character.
What about the empty string?
It has no substrings, so the answer is 0.
How long can the string be?
Up to a few thousand characters, so an O(n^2) method is comfortable and an O(n^3) one is risky.

A careful candidate asks a few questions first. Do equal substrings at different positions count separately? Yes, we count positions, not distinct strings. Do single characters count? Yes. Is the comparison exact, so that A and a differ, and do spaces count? We assume an exact comparison of every character. What about the empty string? It has no substrings, so the answer is 0. How long can the string be? Up to a few thousand characters, so an O(n^2) method is comfortable and an O(n^3) one is risky.

The problem is smaller than it looks. It seems to ask about every one of the many substrings, but we will see that we only need to stand the mirror in 2n - 1 places.

2How to spot the pattern in a question about palindromes

When a beginner first reads this question, the natural plan is to list every substring and test each one, which is correct and which we will try next. The plan treats each substring as a separate little problem. The clues in the question suggest that the substrings are not separate at all.

The first clue is the word substrings, meaning every contiguous run. A string of n characters has about n^2 / 2 of them, n(n + 1) / 2 to be exact, so any plan that does real work for each one separately will be slow. That tells us to look for a way to share work between substrings.

The second clue is the word palindromes. A palindrome is defined by symmetry around its middle, our mirror. If s[l..r], the substring from index l to index r, is a palindrome, then taking one letter off each end leaves s[l+1..r-1], which is also a palindrome with the same middle. So palindromes that share a middle are nested inside each other, like rings around a stone dropped in a pond.

These clues point to the strings and tries family and to a technique called expand around centre. The centre is where the mirror stands, and to expand means to step one character outward on both sides at once. The general rule to carry to new problems is this: when a question is about symmetric pieces of a string, grow each piece outward from its centre and stop at the first mismatch, instead of checking every piece from scratch. The same rule finds the longest palindromic substring.

Some patterns look similar but do not fit as well. Dynamic programming, which stores answers to smaller questions in a table, also works here, because whether s[i..j] is a palindrome depends on s[i+1..j-1], and we will meet it as a middle step. A trie, the tree of prefixes that gives this family its name, helps when matching palindrome pairs across many words, not inside one string. A sliding window does not fit, because being a palindrome cannot be updated by adding one letter on the right and dropping one on the left.

3The honest first attempt, checking every substring

The brute force does what the question literally says. Two loops choose every start i and every end j, and a helper checks whether s[i..j] is a palindrome by walking two indexes inward from the ends, comparing as they go. It is correct and easy to trust, which makes it a good place to start.

Java
static int countSlow(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i; j < s.length(); j++) { // every substring s[i..j]
if (isPalindrome(s, i, j)) count++;
}
}
return count;
}
static boolean isPalindrome(String s, int i, int j) {
while (i < j) {
if (s.charAt(i++) != s.charAt(j--)) return false;
}
return true;
}

Let us count on abba. There are 4 + 3 + 2 + 1 = 10 substrings. The single letters need no comparison. Of the three pairs, ab and ba fail at once and bb passes, one comparison each. The triples abb and bba each fail at the first comparison, and abba takes two. That is only 7 comparisons, but abba is a kind string, because most checks fail at once.

Now generalise. There are about n^2 / 2 substrings, and a check can take up to n / 2 comparisons, so the time is O(n^3), read as order n cubed. The worst case is a string of one repeated letter, where every check succeeds and runs all the way inward: for 3,000 a's that is over two billion comparisons. The extra space is O(1), a few indexes and a counter.

Where is the waste? Look at how abba is checked: first the outer a's are compared, then the inner b's. But the inner b's are exactly the substring bb, which we already checked on its own. Every palindrome check repeats all the work of the smaller palindrome nested inside it. If we started from the inside and grew outward, each larger palindrome would cost one new comparison instead of a whole fresh check.

4Getting to expansion around every centre, one observation at a time

A sensible middle step stores the answers so that nothing is checked twice. Let dp[i][j] be true when s[i..j] is a palindrome. Then dp[i][j] is true exactly when s[i] equals s[j] and the inside, dp[i+1][j-1], is true, and we fill the table for short substrings before long ones. Each cell costs O(1), so the time drops to O(n^2), but the table itself takes O(n^2) memory, about nine million cells for 3,000 characters.

Look at what the table really uses, though. Each palindrome is only ever extended from the one directly inside it, which has the same centre. So we do not need a table at all; we can stand the mirror at one centre, grow outward from it, and move to the next centre. For an odd-length palindrome the centre is a character, so left and right both start at that index. Then, while both indexes are inside the string and s.charAt(left) equals s.charAt(right), the substring between them is a palindrome, so we count it and step left one place left and right one place right.

Now the question every beginner asks. Why do we need gap centres at all? Is a character centre not enough? Let us try abba with character centres only and see what we lose. From each letter we count the letter itself, then compare its two neighbours: at index 1 we compare a with b, and at index 2 we compare b with a, both failures. We find only the four single letters and miss bb and abba completely. An even-length palindrome has no middle letter; its mirror stands between two letters. So for each index we also try the gap after it, starting with left at that index and right at the next one.

Why may we stop at the first mismatch? Because every larger substring around the same centre contains that mismatched pair at the same distance from the middle, so none of them can be a palindrome. Stopping early is not a guess; it is guaranteed to lose nothing.

And why is each palindrome counted exactly once? Every palindrome has exactly one centre, either its middle letter or its middle gap, and from that centre it is reached at exactly one step of the expansion. There are n character centres and n - 1 gaps, 2n - 1 centres in all.

The mistake beginners make most often is forgetting the gap centres, and it is tempting because the odd case alone gives the right answer on strings like abc. Always test with a string that has an even palindrome, such as abba, where the odd-only version returns 4 instead of 6.

A smaller slip is the order of the tests in the while condition. The bounds checks, left >= 0 and right < s.length(), must come before the character comparison, because Java evaluates && from left to right and stops at the first false. Written the other way round, s.charAt(-1) would throw an exception at the first edge.

5Watching the mirror move along abba

The picture runs the code on abba. It tries the centres in the order the loop does: the letter at index 0, then the gap after it, then the letter at index 1, then the gap after that, and so on. left and right mark the two ends being compared, and the panel shows the centre, what was just counted, and the running count.

Watch the gap between the two b's. It is the only centre that finds more than one palindrome, and it shows the nested rings idea most clearly.

Step throughExpanding around every centre of abba

left and right mark the two ends being compared. Marked cells form the palindrome just counted; a pair being compared that fails is shown as compared.

  1. a0b1b2a3leftright
    centre
    letter 0
    counted
    a
    count
    1

    1Centre 0 is the letter a. left and right both start at index 0, a letter always matches itself, so a is counted. Next left falls off the start, so we stop.

  2. a0b1b2a3leftright
    centre
    gap 0|1
    counted
    none
    count
    1

    2The gap between index 0 and 1 is the next centre. left is 0 and right is 1, a and b differ, so nothing is counted here.

  3. a0b1b2a3leftright
    centre
    letter 1
    counted
    b
    count
    2

    3Centre 1 is the first b, which is counted. Moving outward, left is 0 and right is 2, a and b differ, so we stop.

  4. a0b1b2a3leftright
    centre
    gap 1|2
    counted
    bb
    count
    3

    4The gap between the two b's is next. left is 1 and right is 2, b equals b, so bb is a palindrome and count becomes 3.

  5. a0b1b2a3leftright
    centre
    gap 1|2
    counted
    abba
    count
    4

    5We move both ends outward: left is 0 and right is 3. a equals a, so abba is counted with just one more comparison, and count becomes 4.

  6. a0b1b2a3right
    centre
    gap 1|2
    found here
    2
    count
    4

    6Moving out again, left becomes -1 and right becomes 4, both outside the string, so this centre is finished. It found two palindromes.

  7. a0b1b2a3leftright
    centre
    letter 2
    counted
    b
    count
    5

    7Centre 2 is the second b, which is counted. Moving outward, left is 1 and right is 3, b and a differ, so we stop.

  8. a0b1b2a3leftright
    centre
    gap 2|3
    counted
    none
    count
    5

    8The gap between index 2 and 3 is next. b and a differ, so nothing is counted.

  9. a0b1b2a3leftright
    centre
    letter 3
    counted
    a
    count
    6

    9Centre 3 is the last a, which is counted. Moving outward, right becomes 4, past the end of the string, so we stop.

  10. a0b1b2a3leftright
    centre
    gap 3|4
    counted
    none
    total
    6

    10The last even call starts with left 3 and right 4. right is already past the end, so the loop never runs and adds 0. The total is 6.

Let us read the important frames back. The character centres each count their own letter and then stop at the next comparison, except at the two ends, where an index simply runs off the string. The gaps at 0|1 and 2|3 fail at once, because their two letters differ.

The fourth and fifth frames are the heart of the method. At the gap 1|2, b equals b, so bb is counted. Then both ends step outward and a equals a, so abba is counted too, with just one new comparison. Compare that with the brute force, which checked abba from scratch, comparing the b's again.

The last frame shows the final even call, whose right index starts at 4, past the end of the string. The loop condition fails immediately and the call adds nothing, so the total stays at 6, matching the six rows of the first picture.

6The complete Java program

Here is the full program. The method calls a small expand helper twice for each index, once for the character centre and once for the gap to its right. main runs abba, aaa, abc, the empty string and racecar.

Java
public class CountPalindromes {
// Every palindrome has a centre: one character (odd length) or a gap between two (even length).
static int countSubstrings(String s) {
int count = 0;
for (int centre = 0; centre < s.length(); centre++) {
count += expand(s, centre, centre); // odd lengths, centred on s[centre]
count += expand(s, centre, centre + 1); // even lengths, centred between two chars
}
return count;
}
// Grows outward while the ends match; each successful step is one more palindrome.
static int expand(String s, int left, int right) {
int found = 0;
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
found++;
left--;
right++;
}
return found;
}
public static void main(String[] args) {
System.out.println(countSubstrings("abba")); // 6
System.out.println(countSubstrings("aaa")); // 6
System.out.println(countSubstrings("abc")); // 3
System.out.println(countSubstrings("")); // 0
System.out.println(countSubstrings("racecar")); // 10
}
}

Let us read it in the order it runs. countSubstrings starts count at 0 and loops centre over every index. For each one it first calls expand(s, centre, centre), the odd case, where both ends start on the same character, and adds what it returns. Then it calls expand(s, centre, centre + 1), the even case, where the ends start on two neighbouring characters.

Inside expand, found starts at 0. The while condition checks that left has not run off the start, that right has not run off the end, and only then that the two characters match. Each time all three hold, the substring from left to right is one more palindrome, so found goes up by one, and left and right step outward. When any test fails, the loop ends and we return found.

For the last index, the even call starts with right equal to the length of the string, so the bounds test fails at once and it returns 0. That keeps the main loop simple, without a special case for the end. For the empty string the main loop never runs, so the answer is 0.

The printed results match our hand counts, 6 for abba and for aaa, 3 for abc, 0 for the empty string, and 10 for racecar, which has seven single letters plus cec, aceca and racecar.

7How much it costs, and the cases at the edges

Let us count on the example first. abba has 7 centres, and the expansions made 10 character comparisons in all, counting the trivial ones where a letter meets itself. In general there are 2n - 1 centres, and one expansion can take up to about n / 2 steps, so the worst case is O(n^2) time. It is reached by strings of one repeated letter, where every expansion runs all the way to an edge. On ordinary text most expansions stop after a step or two, so it runs much faster than that.

We keep only a few indexes and two counters, so the extra space is O(1). That is the real gain over the table, which reaches the same O(n^2) time but needs O(n^2) memory.

Comparing the ways to count palindromic substrings
ApproachTimeExtra space
Check every substring with two indexesO(n^3)O(1)
Dynamic programming tableO(n^2)O(n^2)
Expand around 2n - 1 centresO(n^2)O(1)
Manacher's algorithmO(n)O(n)

The edge cases are handled without extra code. The empty string returns 0, because the loop never runs. A single character returns 1: its odd call counts it, and its even call returns 0 at once. A string of one repeated letter has n(n + 1) / 2 palindromic substrings, the largest count possible, which still fits in an int for n up to about 65,000; for longer strings we would count in a long.

Strings with no repeated neighbours or mirror pairs, such as abc, give exactly n, one per letter, which is a quick sanity check to say aloud in an interview.

8Follow-up questions

How would you find the longest palindromic substring instead?

We use the same expansion, but instead of counting, we measure. When an expansion stops, left and right have each gone one step too far, so the palindrome just found runs from left + 1 to right - 1 and its length is right - left - 1. We keep the start and length of the longest one seen, and at the end return that substring. It is the same O(n^2) time and O(1) extra space, and it is often the very next question after this one.

Can this be done in linear time?

Yes, with Manacher's algorithm. It visits the centres from left to right and remembers the palindrome that reaches furthest to the right so far. For a new centre inside that palindrome, the mirror image of the centre on the other side already tells us a safe starting radius, so the expansion never re-compares characters known to match. That gives every centre's radius in O(n) total, and the count follows from the radii. It is rarely expected in an interview, but naming it shows depth.

How would you count only distinct palindromic substrings?

Instead of adding one to a counter, we collect the palindromes found during the expansion in a HashSet, either as strings or as pairs of start and end positions turned into a hash of the text, and the answer is the size of the set at the end. A specialised structure called a palindromic tree, or eertree, does it in O(n), but the set is the practical interview answer.

9Conclusion

We counted palindromic substrings by standing a mirror at every centre: each of the n characters and the n - 1 gaps between them, growing outward while the ends match and counting one palindrome per matching step. Because every palindrome has exactly one centre and contains the smaller palindrome around the same centre, each one is counted once, in O(n^2) time and O(1) space, against O(n^3) for checking every substring and O(n^2) memory for the table. The clue to remember: palindromes nest around a centre, so grow them from the inside out, and never forget the even centres.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm: I count every substring that reads the same both ways, by position, so aaa gives six, and single characters count. Checking every substring with two pointers is n cubed.

Then, if they want more

The waste is that checking a palindrome repeats the check of the palindrome inside it, since s from l to r is a palindrome only if the ends match and s from l plus one to r minus one is one. A table over i and j fixes that in n squared time but n squared memory.

Better, I expand around centres. Every palindrome has a centre, either a character for odd lengths or the gap between two characters for even lengths, so there are 2n minus one centres. For each centre I set left and right, and while they are in bounds and the characters match, I count one palindrome and step both outward.

At the first mismatch I stop, because every larger substring around that centre contains the mismatch. In code I call an expand helper twice per index, once with left equal to right and once with right one more. That is O(n squared) in the worst case, such as all a's, and constant extra space.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 18 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How many substrings of a given string are palindromes? Count them.": https://scrivio-interview-library.netlify.app/data-structures/solutions/how-many-substrings-of-a-given-string-are-palindromes-count-them-cb7696/