Palindromic Substrings

Count the palindromes inside a string by growing outward from each letter and from each gap between two letters.

Given a string s, count how many of its substrings are palindromes. A substring is a run of neighbouring letters, such as "bc" in "abc", and a palindrome reads the same from right to left as from left to right. Substrings at different positions count separately, even when their letters are the same.

Example 1
Input: s = "abc"
Output: 3
Explanation: "a", "b", "c".
Example 2
Input: s = "aaa"
Output: 6
Explanation: "a" three times, "aa" twice, and "aaa".
Solution

The Idea

Words such as "noon" and "level" read the same in both directions. Here we hunt for such runs of letters inside one string. In Example 1, "abc", only the three single letters qualify: "ab", "bc" and "abc" all change when read backwards.

Example 2, "aaa", has six: each "a" on its own, the "aa" starting at position 0, the "aa" starting at position 1, and "aaa". The two copies of "aa" sit at different positions, so both count. We could test every substring, but a string of n letters has n(n + 1) / 2 of them. Is there a way to find the palindromes without testing each substring from scratch?

Look at a palindrome from the middle out. "abba" has "bb" in the middle, and "bb" is a palindrome. Wrapping it in one a on each side keeps it a palindrome, because the two added letters are equal. So every palindrome grows from its middle, which we will call its center, one matching pair of letters at a time.

The center can be a letter, like the c in "abcba", which gives an odd length. It can also be the gap between two letters, as in "abba", which gives an even length. "abba" has 4 letters and 3 gaps, so 7 centers. Look at the picture below, which tries all seven.

The seven centers of abba, one per row. Growing outward from each center finds a, nothing, b, then bb and abba, then b, nothing, and a: six palindromes in total.

Each row starts at one center and grows outward while the two end letters match. In the row labelled "on letter 1", the b alone is a palindrome. The next step compares the a at position 0 with the b at position 2, they differ, and the row stops. The highlighted row, "between 1 and 2", finds "bb", then the matching as around it make "abba", and then the string ends. The count column adds up to 6.

Why is the stop safe? Any wider substring around the b at position 1 still holds the a at position 0 and the b at position 2, in mirror places, so none of them can be a palindrome. And every palindrome has exactly one center, so growing from all seven centers counts each palindrome once.

Solution Approach

Three questions shape the code: why not check every substring, how to visit every center, and how far to grow from each one. A table that records which substrings are palindromes reaches the same count in another way.

Checking every substring

Why not simply test every substring? Two loops pick a start and an end, which gives n(n + 1) / 2 substrings, 10 for "abba". Testing one compares letters from both ends inward, up to n / 2 pairs. That adds up to O(n³) work, and much of it repeats: testing "abba" compares the two bs again, although testing "bb" already did.

Visiting every center

How do we reach both kinds of center in one loop? A variable center walks over the positions of s. At each position, a helper method is called twice. The first call grows from the letter itself, with both ends, left and right, on center. The second call grows from the gap after it, with left on center and right on center + 1. After the last letter there is no gap, so right starts past the end and that call finds nothing.

Growing from one center

How far does one center grow? While left and right are both inside the string and their letters match, the substring from left to right is a palindrome, so the count goes up by one. Then left moves one place left and right one place right. The first mismatch, or the end of the string, stops the growth for that center.

A table of palindromes

What if we stored the answers instead? Let dp[i][j] be true when the letters from position i to position j form a palindrome. For "abba", dp[0][3] is true because both ends are a and the inside, dp[1][2] for "bb", is true. A substring of one or two letters only needs its two end letters to match.

If the table is filled so that each inside is ready before its outside, every entry costs one comparison and one lookup. Reusing the stored answer for "bb" when testing "abba", instead of comparing its letters again, is the dynamic programming idea on this problem. The table counts 6 for "abba" too, in O(n²) time, but it needs n² entries of memory. Growing from centers does the same reuse without a table: each step outward builds on the palindrome found by the step before.

Java Solution

The method countSubstrings works in these steps:

  1. First, set count to 0. A loop moves center over every position of s, from 0 to the last.
  2. For each center, call expand(s, center, center) to grow from the letter, then expand(s, center, center + 1) to grow from the gap after it, and add both results to count.
  3. Inside expand, the parameters left and right are the two ends, and a counter found starts at 0. A while loop runs as long as left and right are inside the string and s.charAt(left) equals s.charAt(right). Each pass adds one to found, then moves left down by one and right up by one.
  4. expand returns found. Once the loop over center ends, countSubstrings returns count.

The main method runs both examples, "abba" from the picture, "abcba", a single letter and the empty string.

Java
public class PalindromicSubstrings {

    public static int countSubstrings(String s) {
        int count = 0;
        for (int center = 0; center < s.length(); center++) {
            count += expand(s, center, center);       // odd lengths: center on a letter
            count += expand(s, center, center + 1);   // even lengths: center between letters
        }
        return count;
    }

    // Each step outward whose two ends match is one more palindrome.
    private 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) {
        String[] inputs = {"abc", "aaa", "abba", "abcba", "a", ""};
        for (String s : inputs) {
            System.out.println("\"" + s + "\" -> " + countSubstrings(s));
        }
    }
}

Running it prints:

Output
"abc" -> 3
"aaa" -> 6
"abba" -> 6
"abcba" -> 7
"a" -> 1
"" -> 0

"abc" -> 3 and "aaa" -> 6 are the answers of the two examples. The line "abba" -> 6 matches the count column in the picture, where two of the six, "bb" and "abba", grow from the gap between positions 1 and 2.

In "abcba" -> 7, no two neighbouring letters match, so every gap call returns 0. The seven palindromes are the five single letters, "bcb" and "abcba", the last two grown from the c. For the empty string the loop over center never runs, and the last line shows 0.

The gap call is easy to leave out, and nothing breaks loudly when it is missing. A version that grows only from letters returns 4 for "aaa", losing both copies of "aa". It also returns 4 for "abba", losing "bb" and "abba".

The original implementation, PalindromicSubstrings.java, is on GitHub.

Complexity

The work is the two calls to expand per position, and the steps outward that each call takes.

  • Time: O(n²), because each of the 2n calls to expand moves outward at most about n / 2 times, and a string of one repeated letter, like "aaa", makes the calls near the middle go that far.
  • Space: O(1), because the method keeps only count, center and the two ends left and right, with no table of which substrings are palindromes.

Growing from centers also finds the longest palindrome in a string, instead of counting them all: see Longest Palindromic Substring.