LeetCode Entry
1930. Unique Length-3 Palindromic Subsequences
palindroms subsequences
1930. Unique Length-3 Palindromic Subsequences medium blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1180
Problem TLDR
3-palindroms subsequences #medium
Intuition
// how many pairs we have for alphabet?
// 26*26 - 500*10^5 = 10^7 too big
// a b c d a so, between same chars every uniq counts
// a......b........a.......b can intersect
Approach
- we can use bitmask for speedup
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
// 121ms
fun countPalindromicSubsequence(s: String) =
('a'..'z').sumOf { s.slice(s.indexOf(it)+1..<s.lastIndexOf(it)).toSet().size }
// 127ms
pub fn count_palindromic_subsequence(s: String) -> i32 {
('a'..='z').filter_map(|c| {
let r = s.rfind(c)?; let l = s[..r].find(c)?;
Some(s[l+1..r].chars().unique().count() as i32)
}).sum()
}