1786. Three-Letter Mirrors
A jeweller engraves tiny three-letter marks that read the same forwards and backwards, such as aba or zzz, by picking letters from a long inscription s in order. The picked letters need not be next to each other, but they must keep their left-to-right order in s.
Return the number of distinct three-letter palindromes that occur as a subsequence of s. A palindrome is counted once, no matter how many ways it can be picked, and strings are distinct when they differ in at least one letter. For each letter, only its first and its last occurrence matter: the middle letter must lie strictly between them, so count how many different letters appear in that stretch, using prefix counts of every letter. Intended complexity: O(26 * n) time and O(26 * n) space, or O(26) extra space with a rolling count.
Example 1
- Input:
- s = "abcba"
- Output:
- 3
- Explanation:
Letter a spans bcb and gives aba and aca, letter b spans c and gives bcb, so there are 3 distinct mirrors.
Example 2
- Input:
- s = "aaaa"
- Output:
- 1
- Explanation:
Only aaa can be formed, and it is counted once.
Example 3
- Input:
- s = "abc"
- Output:
- 0
- Explanation:
No letter occurs twice, so no mirror exists and the answer is 0.
Constraints
3 ≤ s.length ≤ 105
s consists of lowercase English letters
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(26 * n)
- Space
- O(26 * n)