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 ss
Example 1
Output: 3
Explanation: "aaa", "aba" and "aca".
Example 2
Output: 0
Explanation: no letter appears twice, so no palindrome of length 3 can be picked.
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"
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 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 firstlastlastfirst
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
Java Solution
The method countPalindromicSubsequence
- First, create two arrays of 26 entries,
andfirst , and filllast with -1 usingfirst . Then one pass overArrays.fill turns each letter into an indexs from 0 to 25 withc , and records its position ins.charAt(i) - 'a' andfirst .last - Next, a loop takes each of the 26 letters
as the outer letter. It skips a letter whosec is still -1, or whosefirst[c] is less than 2 pastlast[c] .first[c] - For each letter left, a new
array starts all false andmiddle starts at 0. Inside, a second loop walks the positions strictly betweendistinct andfirst[c] . Each letter not yet marked inlast[c] is marked and adds 1 tomiddle .distinct - After each outer letter, add
to the running totaldistinct , which starts at 0, and returnresult once all 26 letters are done.result
The main
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:
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
The original implementation,
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
. 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.s - Space: O(1).
,first andlast each have 26 entries, one per letter of the alphabet, however long the string is.middle
For palindromic subsequences of any length, the problem becomes dynamic programming: see