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 s, choose two subsequences of it that are both palindromes and share no index, and return the largest possible product of their lengths. A subsequence keeps some of the letters of s in their original order, and a palindrome reads the same from both ends. The string has 2 to 12 lowercase letters.

Example 1
Input: s = "codingisfun"
Output: 9
Explanation: choose "igi" and "nfn": 3 × 3 = 9.
Example 2
Input: s = "bb"
Output: 1
Explanation: each subsequence is a single "b".
Example 3
Input: s = "accbcaxxcxx"
Output: 25
Explanation: choose "accca" and "xxcxx": 5 × 5 = 25.
Solution

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 string codingisfun with indexes 0 to 10. The row first pick: igi has a 1 under indexes 3, 5 and 6. The row second pick: nfn has a 1 under indexes 4, 8 and 10. No column has a 1 in both rows.

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 int, with bit i standing for index i. Written as a binary number, the row reads right to left: index 0 is the last digit. A number used this way, as a row of yes or no answers, is called a bitmask. Checking that two picks a and b share no letter is then one step: a & b keeps only the bits set in both, and it must be 0.

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 palLen holds, for each bitmask, its length if its letters form a palindrome, and 0 if they do not. The length is the number of 1 bits, which Integer.bitCount counts.

The check itself uses two markers, lo from the left end and hi from the right end. Each marker skips the indexes whose bit is 0, then the two letters they reach are compared. If they differ, the pick is not a palindrome; if they match, both markers move inward and repeat.

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 a? Only those built from the letters a leaves out. Let full be 2n, the number of bitmasks for n letters. Then full - 1 has all n bits set. The ^ operator, exclusive or, turns off the bits of a in it, so rest = (full - 1) ^ a marks exactly the free letters.

Every partner is made from some or all of those free letters, which is called a subset of rest. The update b = (b - 1) & rest, starting from b = rest, visits each of them once. Subtracting 1 turns the lowest 1 bit of b into 0 and the bits below it into 1s. The & rest then keeps only the free positions, so each step gives the next smaller subset of rest.

For example, with rest = 1011 in binary, the walk gives 1011, 1010, 1001, 1000, 0011, 0010 and 0001, then reaches 0 and stops. That is all seven non-empty subsets, and none of them has a 1 where rest has its 0.

How much does this save? Every index ends up in a, in b or in neither, three choices per index. So there are at most 312 = 531,441 pairs to look at, against about 16.8 million.

Java Solution

The method maxProduct works in these steps:

  1. First, store the string's length in n and the number of bitmasks, 2n, in full = 1 << n. Create the table palLen with one entry per bitmask.
  2. Fill the table with a loop over every bitmask mask from 1 up to full - 1. For each one, the helper isPalindrome(s, mask) walks lo and hi inward, skipping indexes not in mask. If it returns true, palLen[mask] gets Integer.bitCount(mask).
  3. Set best to 0. A second loop moves a over every bitmask and skips it when palLen[a] is 0. Otherwise it computes rest = (full - 1) ^ a, the letters a does not use.
  4. Inside, a third loop starts b at rest and steps with b = (b - 1) & rest until b is 0. Each time, best keeps the larger of itself and palLen[a] * palLen[b].
  5. After the loops, best is the answer.

The main method runs the three examples, "ab", which has no palindrome longer than one letter, and a string of twelve a's.

Java
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:

Output
9
1
25
1
36

The values 9, 1 and 25 match the three examples. The 1 for "bb" comes from the rest restriction: if b ran over every bitmask instead, both picks could be "bb", and the method would return 4.

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, MaxProductOfTwoDisjointPalindromes.java, is on GitHub.

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 a, to b or to neither: 531,441 for n = 12.
  • Space: O(2n) for the palLen table, one int per bitmask, which is 4096 entries for n = 12.

The subset walk and bitmasks in general are covered in Bit Manipulation Basics.