Unique Length-3 Palindromic Subsequences

Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Even if a palindrome can be formed in several ways, it is counted once. A subsequence keeps the relative order of characters but may delete some of them.

30:00

Unique Length-3 Palindromic Subsequences
medium
Free written solution
Topics
Companies

Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Even if a palindrome can be formed in several ways, it is counted once. A subsequence keeps the relative order of characters but may delete some of them.

Example 1:
Input: {"s":"aabca"}
Output: 3
Constraints:
  • 3≤s.length≤1053 \leq s.length \leq 10^5

  • s consists of only lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"aabca"}

A length-3 palindrome is x?x. For each outer letter x, use its first and last positions: any letter strictly between them can be the middle.

scan s once for first and last positions

n = 5

a0
a1
b2
c3
a4

scanning

first / last of outer letter

candidate middles

26-bit mask of distinct middles

mask = 0

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z

first / last per letter

count = 0

no letters seen yet

Variables
VariableValue
n5
DepthFunction Call
Stack empty
0/14