Maximum Product of The Length of Two Palindromic Subsequences
Pick two palindromes from the letters of one string, sharing no letter, so that the product of their lengths is as large as possible.
Given a string ss
Example 1
Output: 9
Explanation: choose "igi" and "nfn": 3 × 3 = 9.
Example 2
Output: 1
Explanation: each subsequence is a single "b".
Example 3
Output: 25
Explanation: choose "accca" and "xxcxx": 5 × 5 = 25.
The Idea
You have probably met palindromes before: words like "level" or "noon" that read the same from either end. Here we make them by crossing out letters of a string. Whatever is left, read in order, is a subsequence. In "codingisfun", keeping only the i at index 3, the g at index 5 and the i at index 6 leaves "igi", a palindrome.
The problem wants two such picks at once, and no letter may go to both. Example 1 pairs "igi" with "nfn", made from the n at index 4, the f at index 8 and the n at index 10. Each has three letters, so the product is 9. Example 2 shows why the rule matters. "bb" is itself a palindrome of length 2, but it uses both letters and leaves nothing for a second pick, so the best is "b" and "b", 1 × 1 = 1.
So how do we find the best pair? The kept letters need not sit next to each other, and the two picks can weave between each other, as "igi" and "nfn" do. There is no simple pattern to follow. But the string is short, at most 12 letters, and each letter is either kept in a pick or not. That gives 212 = 4096 possible picks, few enough to try them all.
How do we write a pick down? As a row of 0s and 1s, one under each letter, where 1 means the letter is kept. Look at the picture below.
The row labelled "first pick: igi" has a 1 under indexes 3, 5 and 6, and the row labelled "second pick: nfn" has a 1 under indexes 4, 8 and 10. No column has a 1 in both rows, and that is exactly the rule that the two picks share no letter.
A row of 0s and 1s is also how a computer stores a whole number in binary, where each 0 or 1 is one bit. So each pick fits in a single intiiaba & b
Solution Approach
Trying every pair of picks directly is slow, so the solution settles two things instead: how to tell which picks are palindromes, and how to find partners for a pick that share no letter with it.
Trying every pair of picks
Why not pair every bitmask with every other one? For 12 letters that is 4096 × 4096, about 16.8 million pairs. Most of them share letters and are thrown away, and each palindrome check would read the string again, many times over for the same bitmask.
Which picks are palindromes
Whether a pick is a palindrome does not depend on its partner, so each bitmask is checked once and the result is stored. The table palLenInteger.bitCount
The check itself uses two markers, lohi
Storing 0 for a non-palindrome has a handy side effect. A product with a non-palindrome partner is then 0, so it can never become the best answer, and no separate check is needed.
Partners that share no letter
Which bitmasks can be partners of a palindrome aafullfull - 1^arest = (full - 1) ^ a
Every partner is made from some or all of those free letters, which is called a subset of restb = (b - 1) & restb = restb& restrest
For example, with restrest
How much does this save? Every index ends up in ab
Java Solution
The method maxProduct
- First, store the string's length in
and the number of bitmasks, 2n, inn . Create the tablefull = 1 << n with one entry per bitmask.palLen - Fill the table with a loop over every bitmask
from 1 up tomask . For each one, the helperfull - 1 walksisPalindrome(s, mask) andlo inward, skipping indexes not inhi . If it returns true,mask getspalLen[mask] .Integer.bitCount(mask) - Set
to 0. A second loop movesbest over every bitmask and skips it whena is 0. Otherwise it computespalLen[a] , the lettersrest = (full - 1) ^ a does not use.a - Inside, a third loop starts
atb and steps withrest untilb = (b - 1) & rest is 0. Each time,b keeps the larger of itself andbest .palLen[a] * palLen[b] - After the loops,
is the answer.best
The main
public class MaximumProductOfTheLengthOfTwoPalindromicSubsequences {
public static int maxProduct(String s) {
int n = s.length();
int full = 1 << n; // number of masks: 2 to the power n
int[] palLen = new int[full]; // palLen[mask]: its length if a palindrome, else 0
for (int mask = 1; mask < full; mask++) {
if (isPalindrome(s, mask)) {
palLen[mask] = Integer.bitCount(mask);
}
}
int best = 0;
for (int a = 1; a < full; a++) {
if (palLen[a] == 0) {
continue; // a is not a palindrome
}
int rest = (full - 1) ^ a; // indices that a does not use
for (int b = rest; b > 0; b = (b - 1) & rest) { // every subset of rest
best = Math.max(best, palLen[a] * palLen[b]);
}
}
return best;
}
private static boolean isPalindrome(String s, int mask) {
int lo = 0;
int hi = s.length() - 1;
while (lo < hi) {
while (lo < hi && (mask & (1 << lo)) == 0) {
lo++; // skip indices not in the subsequence
}
while (lo < hi && (mask & (1 << hi)) == 0) {
hi--;
}
if (s.charAt(lo) != s.charAt(hi)) {
return false;
}
lo++;
hi--;
}
return true;
}
public static void main(String[] args) {
System.out.println(maxProduct("codingisfun"));
System.out.println(maxProduct("bb"));
System.out.println(maxProduct("accbcaxxcxx"));
System.out.println(maxProduct("ab"));
System.out.println(maxProduct("a".repeat(12)));
}
}
Running it prints:
9
1
25
1
36
The values 9, 1 and 25 match the three examples. The 1 for "bb" comes from the restb
The fourth line, for "ab", is 1 because "a" and "b" differ, so no pick longer than one letter is a palindrome. Look at the last line, 36. With twelve a's every pick is a palindrome, so the question becomes how to split twelve letters into two groups, and 6 × 6 = 36 beats 5 × 7 = 35.
The original implementation,
Complexity
The work is one palindrome check per bitmask, plus one step for every pair of picks that share no letter.
- Time: O(2n × n + 3n). Each of the 2n bitmasks gets one palindrome check, which reads up to n letters. The pairs cost 3n, because each index goes to
, toa or to neither: 531,441 for n = 12.b - Space: O(2n) for the
table, onepalLen per bitmask, which is 4096 entries for n = 12.int
The subset walk and bitmasks in general are covered in