Count Magical Substring Pairs I Problem
Description
LeetCode Problem 4090.
You are given a string s of length n consisting of lowercase English letters.
For every triplet of indices (i, j, k) satisfying 0 <= i <= j < k < n, define:
s1 = s[i..j]s2 = s[j + 1..k]
A pair of substrings (s1, s2) is called magical if the number of distinct characters in s1 is equal to the number of distinct characters in s2.
Return the number of triplets (i, j, k) for which (s1, s2) is a magical pair.
Example 1:
Input: s = "aba"
Output: 2
Explanation:
There are 2 valid triplets:
No. (i, j, k) s1 s2 distinct(s1) distinct(s2)
1 (0, 0, 1) "a" "b" 1 1
2 (1, 1, 2) "b" "a" 1 1
Example 2:
Input: s = "kkk"
Output: 4
Explanation:
There are 4 valid triplets:
No. (i, j, k) s1 s2 distinct(s1) distinct(s2)
1 (0, 0, 1) "k" "k" 1 1
2 (0, 0, 2) "k" "kk" 1 1
3 (0, 1, 2) "kk" "k" 1 1
4 (1, 1, 2) "k" "k" 1 1
Example 3:
Input: s = "abcac"
Output: 7
Explanation:
There are 7 valid triplets:
No. (i, j, k) s1 s2 distinct(s1) distinct(s2)
1 (0, 0, 1) "a" "b" 1 1
2 (1, 1, 2) "b" "c" 1 1
3 (2, 2, 3) "c" "a" 1 1
4 (3, 3, 4) "a" "c" 1 1
5 (0, 1, 3) "ab" "ca" 2 2
6 (0, 1, 4) "ab" "cac" 2 2
7 (1, 2, 4) "bc" "ac" 2 2
Constraints:
2 <= s.length <= 2000sconsists of lowercase English letters.
Solution
Approach: Enumerate the Split Point
Choose the split j (the last index of s1). For each start i from j down to 0, keep a frequency table of s[i..j]; its size is the number of distinct characters. Record in cnt[d] how many starts give exactly d distinct characters.
Then extend the right part: for k from j + 1 to n - 1, keep a second frequency table of s[j+1..k] and add cnt[d] for its current distinct count d. Summing over all splits counts every magical triplet once.
Complexity: O(n2) time and O(1) space, since the alphabet has only 26 letters.
from collections import defaultdict
class Solution:
def countMagicalPairs(self, s: str) -> int:
n = len(s)
ans = 0
for j in range(n - 1):
cnt1 = defaultdict(int)
cnt = [0] * 27
for i in range(j, -1, -1):
cnt1[s[i]] += 1
cnt[len(cnt1)] += 1
cnt2 = defaultdict(int)
for k in range(j + 1, n):
cnt2[s[k]] += 1
ans += cnt[len(cnt2)]
return ans