medium Unique Length-3 Palindromic Subsequences
Problem Statement
Given a string s, return the total number of unique palindromes of length 3 which are subsequences of s. Even if multiple ways exist to obtain the same subsequence, it is still only counted once.
A palindrome string is a sequence of characters that reads the same backward as forward.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Examples
Example 1:
- Input: s = "abcba"
- Expected Output: 3
- Justification: The three unique length-3 palindromic subsequences are "aba", "aca", and "bcb".
Example 2:
- Input: s = "aba"
- Expected Output: 1
- Justification: The one unique length-3 palindromic subsequence is "aba".
Example 3:
- Input: s = "aacbbcacb"
- Expected Output: 9
- Justification: The nine unique length-3 palindromic subsequences are "aaa", "aca", "aba", "ccc", "cbc", "bbb", "bab", "cac", and "bcb".
Try it yourself
Try solving this question here:
✅ Solution Unique Length-3 Palindromic Subsequences
Problem Statement
Given a string s, return the total number of unique palindromes of length 3 which are subsequences of s. Even if multiple ways exist to obtain the same subsequence, it is still only counted once.
A palindrome string is a sequence of characters that reads the same backward as forward.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Examples
Example 1:
- Input: s = "abcba"
- Expected Output: 3
- Justification: The three unique length-3 palindromic subsequences are "aba", "aca", and "bcb".
Example 2:
- Input: s = "aba"
- Expected Output: 1
- Justification: The one unique length-3 palindromic subsequence is "aba".
Example 3:
- Input: s = "aacbbcacb"
- Expected Output: 9
- Justification: The nine unique length-3 palindromic subsequences are "aaa", "aca", "aba", "ccc", "cbc", "bbb", "bab", "cac", and "bcb".
Solution
To solve this problem, we will utilize a combination of hashing and set operations to track the unique palindromic subsequences efficiently. The core idea revolves around identifying all the distinct characters that can act as the middle character of a length-3 palindrome and finding if there are corresponding matching characters on either side of each occurrence of this middle character. This approach is effective because it directly targets the structure of the problem — leveraging the fact that for a sequence to be a palindrome of length 3, the first and third characters must be the same, with any character in between.
The algorithm's efficiency comes from minimizing the search space to only those characters that could potentially form a palindrome, rather than exhaustively checking every possible subsequence combination. By doing so, we significantly reduce computational complexity while ensuring that no potential palindrome is overlooked.
Step-by-Step Algorithm
-
Initialize a Set: Start by creating an empty set,
uniquePalindromes, which will store all unique palindromic subsequences of length 3 found in the input string. -
Iterate Over Alphabet: Loop through all lowercase English letters ('a' to 'z'). For each character,
c, perform the following steps:- Find First and Last Occurrences: Determine the first and last positions of
cin the input string,s, usingindexOfandlastIndexOfmethods (or their equivalents in other languages). Let's denote these positions asfirstandlast, respectively. - Check for Validity: Ensure that
firstis less thanlast. This condition confirms that there are characters between the first and last occurrences ofc, which is necessary for forming a palindrome of length 3. - Explore Middle Characters: If the above condition holds, iterate over the substring of
sthat lies betweenfirstandlast(exclusive). For each character,m, in this substring:- Form Palindrome: Construct a palindromic subsequence by placing
mbetween twocs (i.e.,cmc). - Add to Set: Add this palindromic subsequence to
uniquePalindromesset.
- Form Palindrome: Construct a palindromic subsequence by placing
- Find First and Last Occurrences: Determine the first and last positions of
-
Return Result: After completing the above steps for every letter in the alphabet, the size of
uniquePalindromesset represents the total number of unique palindromic subsequences of length 3 in the input string. Return this count as the final result.
Algorithm Walkthrough
Let's consider the input: s = "aacbbcacb".
-
Initialize
uniquePalindromesSet: An empty set that will hold all unique length-3 palindromic subsequences found in the string. -
Iterate Over Alphabet to Find Unique Palindromes:
-
For 'a':
- First occurrence is at position 0, and the last occurrence is at position 6.
- Between these positions, the characters are "acbbc".
- From these characters, you can form "aaa", "aca", and "aba" by selecting different characters between the first and last 'a'.
- Add "aaa", "aba", and "aca" to the set.
-
For 'b':
- First occurrence is at position 3, and the last occurrence is at position 8.
- Between these positions, the characters are "bcac".
- From these characters, "bbb", "bcb", and "bab" can be formed by selecting different characters between the first and last 'b'.
- Add "bbb", "bcb", and "bab" to the set.
-
For 'c':
- The first position of 'c' is 2, and the last is 7.
- Between these positions, the characters are "bbca".
- From these, "cbc", "ccc", and "cac" palindromes can be formed by selecting different characters between the first and last 'c'.
- Add "ccc", "cbc", and "cac" to the set.
-
-
After Iterating Through Relevant Characters ('a', 'b', 'c'):
- The
uniquePalindromesset contains the subsequences "aaa", "aba", "aca", "bbb", "bcb", "bab", "ccc", "cbc", and "cac".
- The
-
Count the Unique Palindromic Subsequences:
- The total count of unique palindromic subsequences in the set is 9, which matches the expected output.
-
Return the Total Count: The algorithm concludes that there are 9 unique palindromic subsequences of length 3 in "aacbbcacb", which are "aaa", "aca", "aba", "ccc", "cbc", "bbb", "bab", "cac", and "bcb".
Code
import java.util.HashSet;
import java.util.Set;
public class Solution {
// Method to count unique palindromic subsequences
public int countPalindromicSubsequence(String s) {
Set<String> uniquePalindromes = new HashSet<>();
for (char c = 'a'; c <= 'z'; c++) {
int first = s.indexOf(c);
int last = s.lastIndexOf(c);
if (first < last) { // Ensure there are characters in between
for (int j = first + 1; j < last; j++) {
uniquePalindromes.add("" + c + s.charAt(j) + c);
}
}
}
return uniquePalindromes.size();
}
// Main method to test the algorithm with provided examples
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.countPalindromicSubsequence("abcba")); // 3
System.out.println(solution.countPalindromicSubsequence("aba")); // 1
System.out.println(solution.countPalindromicSubsequence("aacbbcacb")); // 9
}
}
Complexity Analysis
Time Complexity
The overall time complexity of the algorithm is
Space Complexity
The space complexity of the algorithm is s is the number of unique palindromic subsequences that can be formed.
🤖 Don't fully get this? Learn it with Claude
Stuck on Unique Length-3 Palindromic Subsequences? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Unique Length-3 Palindromic Subsequences** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Unique Length-3 Palindromic Subsequences** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Unique Length-3 Palindromic Subsequences**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Unique Length-3 Palindromic Subsequences**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.