Unique Length-3 Palindromic Subsequences

Count the different three-letter palindromes you can pick from a string, keeping its letters in order.

Given a string s of lowercase English letters, return how many different palindromes of length 3 are subsequences of s. A palindrome reads the same forwards and backwards. A subsequence is what is left after deleting some letters, or none, without changing the order of the rest. Each different palindrome counts once, however many ways it can be picked.

Example 1
Input: s = "aabca"
Output: 3
Explanation: "aaa", "aba" and "aca".
Example 2
Input: s = "adc"
Output: 0
Explanation: no letter appears twice, so no palindrome of length 3 can be picked.
Solution

The Idea

Words like "eye", "mom" and "pop" are palindromes of length 3: read backwards, they stay the same. In each of them the first and last letters match, and the middle letter can be anything. That is the whole shape: a letter, any letter, then the first letter again.

Now take "aabca" from Example 1, with positions numbered 0 to 4. The letters at positions 0, 2 and 4 are a, b and a, which spell "aba". Positions 1, 2 and 4 spell "aba" as well, but the same palindrome still counts once. Positions 0, 1 and 2 spell "aab", which is not a palindrome. Five letters allow 10 picks of three positions, and only three different palindromes come out of them.

So for a given outer letter, which middle letters are possible? Take a, which appears at positions 0, 1 and 4. A middle letter has to sit between one a and a later a. The widest such pair is the first a and the last a, and every other pair of a's lies inside it. So any middle letter that works for some pair of a's also lies between the first and the last a. Look at the picture below.

The string aabca at positions 0 to 4. The first a is at 0 and the last a at 4. The letters between them are a, b and c, which give the palindromes aaa, aba and aca.

The boxes marked "first a" and "last a", at positions 0 and 4, are the outer pair. The bracket under the three boxes between them reads "letters between: a, b, c", and each of those letters gives one palindrome: "aaa", "aba" and "aca". The letters b and c appear only once, so neither can be an outer letter, and the answer is 3.

That turns the search into counting. For each letter, count the different letters between its first and last position, and add these counts up over all letters.

Solution Approach

Turning that idea into code means settling three things: how to find each letter's first and last position, which letters to skip, and how to count each middle letter only once. First, though, a look at why trying every pick of three positions is too slow.

Trying every pick of three positions

Why not try every pick of three positions and keep the palindromes in a set, a collection that stores each value only once? The set would take care of the repeats. But the number of picks grows fast: 10 for five letters, but 166,167,000 for 1,000 letters. Working from the outer pairs needs one short scan per letter instead.

First and last position of each letter

Where does each letter start and end? Two arrays with 26 entries, one entry per letter from a to z, hold the answer. One pass over the string writes the position into first the first time a letter is seen, and into last every time, so last ends up with the final position. first starts filled with -1, which means the letter has not appeared.

Letters that give nothing

Which letters can be skipped? A letter that never appears, and a letter whose first and last positions are less than 2 apart. In "aa", the two a's sit next to each other, so there is no room for a middle letter.

Counting each middle letter once

How do we count different letters rather than positions? In "aaaa", the first and last a hold two letters between them, both a, yet they make only one palindrome, "aaa". A third array, middle, has 26 true-or-false entries and remembers which letters were already seen between the outer pair. Only a letter seen for the first time adds 1 to the count.

Java Solution

The method countPalindromicSubsequence works in these steps:

  1. First, create two arrays of 26 entries, first and last, and fill first with -1 using Arrays.fill. Then one pass over s turns each letter into an index c from 0 to 25 with s.charAt(i) - 'a', and records its position in first and last.
  2. Next, a loop takes each of the 26 letters c as the outer letter. It skips a letter whose first[c] is still -1, or whose last[c] is less than 2 past first[c].
  3. For each letter left, a new middle array starts all false and distinct starts at 0. Inside, a second loop walks the positions strictly between first[c] and last[c]. Each letter not yet marked in middle is marked and adds 1 to distinct.
  4. After each outer letter, add distinct to the running total result, which starts at 0, and return result once all 26 letters are done.

The main method runs both examples, a longer string with two usable outer letters, "aaaa" with a repeated middle letter, and "aa" with no room for a middle.

Java
import java.util.Arrays;

public class UniqueLength3PalindromicSubsequences {

    public static int countPalindromicSubsequence(String s) {
        int[] first = new int[26];
        int[] last = new int[26];
        Arrays.fill(first, -1);                  // -1: the letter has not appeared yet
        for (int i = 0; i < s.length(); i++) {
            int c = s.charAt(i) - 'a';
            if (first[c] == -1) {
                first[c] = i;
            }
            last[c] = i;
        }
        int result = 0;
        for (int c = 0; c < 26; c++) {           // c is the outer letter of "c?c"
            if (first[c] == -1 || last[c] - first[c] < 2) {
                continue;                        // missing, or no room for a middle letter
            }
            boolean[] middle = new boolean[26];
            int distinct = 0;
            for (int i = first[c] + 1; i < last[c]; i++) {
                int m = s.charAt(i) - 'a';
                if (!middle[m]) {
                    middle[m] = true;
                    distinct++;                  // each new middle letter is one palindrome
                }
            }
            result += distinct;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(countPalindromicSubsequence("aabca"));
        System.out.println(countPalindromicSubsequence("adc"));
        System.out.println(countPalindromicSubsequence("bbcbaba"));
        System.out.println(countPalindromicSubsequence("aaaa"));
        System.out.println(countPalindromicSubsequence("aa"));
    }
}

Running it prints:

Output
3
0
4
1
0

The 3 and the 0 at the top match the two examples. The third line, 4, comes from "bbcbaba". Its first b is at position 0 and its last b at 5, with b, c, b and a between them: three different letters, giving "bbb", "bcb" and "bab". The a's at positions 4 and 6 hold one b, which gives "aba", and the single c gives nothing.

The fourth line is 1. "aaaa" has two positions between its outer a's, but both hold an a, so middle lets only the first one count, and "aaa" is counted once. The last line is 0, because "aa" has no letter between its two a's.

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

Complexity

The work is one pass to find each letter's outer pair, plus one scan between the outer pair for each of the 26 letters.

  • Time: O(26 × n), which is O(n), where n is the length of s. The first pass reads each letter once, and each of the 26 scans reads at most the letters between one letter's first and last position, never more than n.
  • Space: O(1). first, last and middle each have 26 entries, one per letter of the alphabet, however long the string is.

For palindromic subsequences of any length, the problem becomes dynamic programming: see Longest Palindromic Subsequence.