Unique Length-3 Palindromic Subsequences (LeetCode 1930): Solution and Explanation
Given a lowercase string s, count how many different length-3 palindromes can be picked out of it as subsequences. A palindrome that can be formed in several ways still counts once, so for "aabca" the answer is 3: aba, aaa and aca.
Intuition
Trying every triple of positions is O(n^3) and far too slow for 10^5 characters. The way out is to notice how little a length-3 palindrome contains: it is always x?x, an outer letter repeated at both ends with any letter in the middle. With 26 choices for each there are at most 676 different answers, so we should count by letter pairs, not by positions.
Fix the outer letter x. A middle letter y works if some y sits strictly between an x and a later x. Stretching the window can only add candidates, so the best window runs from the first x in the string to the last x. Any y inside that window works, and any y outside it cannot work for any pair of x's.
That turns the problem into: for each letter, how many distinct letters lie strictly between its first and last occurrence? A 26-bit mask answers it neatly. OR in 1 << letter for each character in the window; repeats set the same bit, so the number of set bits is the number of distinct middles.
Letters that appear once, or whose two copies are adjacent, have an empty window and contribute nothing.
Approach: First and last occurrence with a letter mask
- Scan s once. For each letter record
first[c], the index where it first appears, andlast[c], the index where it last appears. - For each letter c with
last[c] - first[c] >= 2, build a mask by OR-ing1 << (s[j] - 'a')for every j strictly between first[c] and last[c]. - Count the set bits of the mask with
mask &= mask - 1and add that count to the answer. - Return the total.
Step-by-step example
s = "aabca"
- The scan gives a: first 0, last 4; b: first 2, last 2; c: first 3, last 3.
- Outer 'a': the window is indices 1..3, holding a, b, c. The mask has 3 bits, giving aaa, aba and aca. count = 3.
- Outer 'b' appears once, so it is skipped.
- Outer 'c' appears once, so it is skipped.
- Return 3.
Code: Python, Java, C++
1class Solution:
2 def countPalindromicSubsequence(self, s: str) -> int:
3 first = [-1] * 26
4 last = [-1] * 26
5 for i, ch in enumerate(s):
6 c = ord(ch) - 97
7 if first[c] == -1:
8 first[c] = i
9 last[c] = i
10 count = 0
11 for c in range(26):
12 if last[c] - first[c] < 2:
13 continue
14 mask = 0
15 for j in range(first[c] + 1, last[c]):
16 mask |= 1 << (ord(s[j]) - 97)
17 while mask:
18 mask &= mask - 1
19 count += 1
20 return count1class Solution {
2 public int countPalindromicSubsequence(String s) {
3 int[] first = new int[26];
4 int[] last = new int[26];
5 Arrays.fill(first, -1);
6 Arrays.fill(last, -1);
7 for (int i = 0; i < s.length(); i++) {
8 int c = s.charAt(i) - 'a';
9 if (first[c] == -1) first[c] = i;
10 last[c] = i;
11 }
12 int count = 0;
13 for (int c = 0; c < 26; c++) {
14 if (last[c] - first[c] < 2) continue;
15 int mask = 0;
16 for (int j = first[c] + 1; j < last[c]; j++) {
17 mask |= 1 << (s.charAt(j) - 'a');
18 }
19 while (mask != 0) {
20 mask &= mask - 1;
21 count++;
22 }
23 }
24 return count;
25 }
26}1class Solution {
2public:
3 int countPalindromicSubsequence(string s) {
4 vector<int> first(26, -1);
5 vector<int> last(26, -1);
6 for (int i = 0; i < (int)s.size(); i++) {
7 int c = s[i] - 'a';
8 if (first[c] == -1) first[c] = i;
9 last[c] = i;
10 }
11 int count = 0;
12 for (int c = 0; c < 26; c++) {
13 if (last[c] - first[c] < 2) continue;
14 int mask = 0;
15 for (int j = first[c] + 1; j < last[c]; j++) {
16 mask |= 1 << (s[j] - 'a');
17 }
18 while (mask != 0) {
19 mask &= mask - 1;
20 count++;
21 }
22 }
23 return count;
24 }
25};Time and space complexity
O(26 * n)
The first pass is O(n). Each of the 26 letters then scans at most n characters of its window.
O(1)
Two arrays of 26 integers and a single mask, independent of n.
Other approaches
Set of middles per letter (time O(26 * n), space O(n))
Same first and last idea, but collect the window into a hash set, for example len(set(s[first+1:last])) in Python. Shorter to write, slightly more memory.
Prefix counts (time O(26 * n), space O(26 * n))
Precompute prefix counts of every letter. Then letter y is a valid middle for x when prefix[last][y] - prefix[first + 1][y] > 0, which makes each check O(1) after O(26n) preprocessing.
Brute force over triples (time O(n^3), space O(1))
Check every i < j < k with s[i] == s[k] and store the strings in a set. Correct but O(n^3).
Common mistakes
- Counting ways instead of distinct palindromes. "aaaa" has four ways to pick aaa but the answer is 1.
- Including first[c] or last[c] in the window. The middle must be strictly between the two ends; including them would wrongly count x x x whenever x appears only twice.
- Forgetting that the middle may equal the outer letter. In "aaa" the palindrome aaa is valid, and the a at index 1 sets the 'a' bit in the mask.
- Using a nested loop over every pair of x positions, which turns an O(26n) solution back into O(n^2).
Frequently asked questions
Why is the first and last occurrence enough?
Any palindrome x y x uses some x before y and some x after it. The first x in the string is at or before that one, and the last x is at or after the other, so y is also inside the widest window. Nothing is lost by only looking there.
Why use a bitmask instead of a set?
There are only 26 letters, so an int holds the whole set. OR adds a letter and popcount gives the size, with no allocation.
What is the largest possible answer?
676, which is 26 outer letters times 26 middle letters. It is reached when every letter appears at both ends of a window that contains all 26 letters.