Problem Description
Given a string s, find two disjoint palindromic subsequences where no character index is shared between them such that the product of their lengths is maximized. A subsequence is formed by deleting some or no characters from s without changing the order of the remaining characters, and a palindromic subsequence reads the same forwards and backwards.
Key Insights
- Because the length of s is at most 12, the total number of subsequences (2^n) is manageable.
- Represent each subsequence using a bit mask indicating the chosen indices.
- Check if a subsequence is a palindrome by constructing the subsequence from the bit mask and comparing it to its reverse.
- Store each valid mask along with its palindrome length.
- Iterate over all pairs of masks; ensure they are disjoint (i.e., bitwise AND == 0) and maximize the product of their stored lengths.
Space and Time Complexity
Time Complexity: O(2^n * n + (2^n)^2)
Space Complexity: O(2^n)
(Note: n is the length of string s, which is at most 12)
Solution
The solution uses bit masking to enumerate all subsequences of s. For each possible bitmask from 0 to 2^n - 1:
- Construct the subsequence using indices where the bitmask has a 1.
- Check if the generated subsequence is a palindrome.
- If yes, record the mask and its length. After processing all subsequences, use a double loop to iterate over pairs of valid masks. For each pair, check if the two bitmasks are disjoint (i.e., they do not share any index) by verifying (mask1 & mask2) == 0. If disjoint, compute the product of their lengths and update the maximum found product.