Problem Description
Given a string s, count the number of unique palindromic subsequences of length 3 that can be found as a subsequence in s. A palindromic sequence of length 3 has the form "a b a", where a and b are any characters. Even if the same sequence can be formed in multiple ways, it should only be counted once.
Key Insights
- A valid palindrome of length 3 has the structure "a? a" where the first and last characters are the same.
- For each character from 'a' to 'z', identify the first and last occurrence in the string.
- Only if a character appears at least twice, there can be a valid palindrome with that character as both the first and last letter.
- The middle character can be any distinct character that appears between the first and last occurrence of the outer character.
- Using precomputation (like prefix sums or sets) optimizes the retrieval of unique mid characters between specific indices.
Space and Time Complexity
Time Complexity: O(n + 26*26) which is effectively O(n) since the alphabet size is constant. Space Complexity: O(n) if using auxiliary data structures such as prefix arrays or sets; otherwise O(1) additional space for constant size storage.
Solution
The approach involves these steps:
- Scan the string once to record the first and last positions for each letter.
- For each letter (from 'a' to 'z') that appears at least twice in the string, collect the unique characters (middle letters) that occur between its first and last positions.
- The count of unique length-3 palindromic subsequences contributed by that letter will be equal to the number of unique middle characters found.
- Sum all such counts to get the final answer.
Data Structures and Techniques:
- Arrays or dictionaries to store first and last occurrence indices for each letter.
- A set to accumulate unique middle characters between the two positions.
- Iteration over the constant-size alphabet ensures a time complexity linear in the string length.
Code Solutions
Below are the code implementations in Python, JavaScript, C++, and Java.