Unique Length-3 Palindromic Subsequences - Problem

Given a string s, return the number of unique palindromes of length three that are a subsequence of s.

Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.

A palindrome is a string that reads the same forwards and backwards.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

For example, "ace" is a subsequence of "abcde".

Input & Output

Example 1 — Basic Case
$ Input: s = "aabca"
Output: 3
💡 Note: The 3 palindromic subsequences of length 3 are: "aaa" (using s[0], s[1], s[4]), "aba" (using s[0], s[2], s[4]), and "aca" (using s[0], s[3], s[4]). Note that "aaa" uses the first two 'a's and the last 'a'.
Example 2 — No Palindromes
$ Input: s = "abc"
Output: 0
💡 Note: There are no characters that appear more than once, so no palindromic subsequences of length 3 can be formed.
Example 3 — Multiple Occurrences
$ Input: s = "bbcacaba"
Output: 6
💡 Note: The palindromes are: For 'b' (positions 0,1,6,7): 'bab', 'bcb', 'bbb' using middle chars {a,b,c}. For 'c' (positions 2,4): 'cac' using middle char {a}. For 'a' (positions 3,5,6): 'aca', 'aaa' using middle chars {c,a}. Total: 3+1+2=6 unique palindromes.

Constraints

  • 3 ≤ s.length ≤ 105
  • s consists of only lowercase English letters

Visualization

Tap to expand
Unique Length-3 Palindromic Subsequences INPUT String s = "aabca" a 0 a 1 b 2 c 3 a 4 First Occurrence Array a: 0 b: 2 c: 3 Last Occurrence Array a: 4 b: 2 c: 3 Palindrome form: X_Y_X First char = Last char Middle can be any char ALGORITHM STEPS 1 Find First/Last Index Store first and last pos for each unique char 2 For Each Character Check if first != last (chars between them) 3 Count Unique Middle Count distinct chars between first and last 4 Sum All Counts Add unique palindromes for each outer char Processing 'a' (idx 0 to 4): Between: a[a,b,c]a Unique middle: {a,b,c} Palindromes: aaa,aba,aca FINAL RESULT Found Palindromic Subsequences: "aaa" a[0] + a[1] + a[4] "aba" a[0] + b[2] + a[4] "aca" a[0] + c[3] + a[4] 'b' and 'c': first == last (no chars between) OUTPUT 3 Key Insight: For a length-3 palindrome XYX, the first and last characters must be the same. Using arrays to track first/last occurrence of each character, we can efficiently count unique middle characters between them. Time: O(26*n), Space: O(26) = O(1). TutorialsPoint - Unique Length-3 Palindromic Subsequences | Optimized with Arrays
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen