Unique Substrings With Equal Digit Frequency Problem
Description
LeetCode Problem 2168.
Given a digit string s, return the number of unique substrings of s where every digit appears the same number of times.
Example 1:
Input: s = "1212"
Output: 5
Explanation: The substrings that meet the requirements are "1", "2", "12", "21", "1212".
Note that although the substring "12" appears twice, it is only counted once.
Example 2:
Input: s = "12321"
Output: 9
Explanation: The substrings that meet the requirements are "1", "2", "3", "12", "23", "32", "21", "123", "321".
Constraints:
1 <= s.length <= 1000sconsists of digits.
Solution
Approach: Prefix counts and a hash set
Build prefix counts presum[i][d], the number of times digit d appears in the first i characters. The count of each digit in a substring s[i..j] is then a difference of two prefix rows.
Enumerate every substring. It is valid when all digits that appear in it have the same count, which we check by collecting the non-zero counts of the ten digits into a set and requiring at most one distinct value. Valid substrings go into a hash set, so equal substrings are counted once. The answer is the size of the set.
Complexity: time O(n^2 * (10 + n)) including hashing the substrings, space O(n^3) in the worst case for the set of strings (n <= 1000).
class Solution:
def equalDigitFrequency(self, s: str) -> int:
def check(i, j):
v = set()
for k in range(10):
cnt = presum[j + 1][k] - presum[i][k]
if cnt > 0:
v.add(cnt)
if len(v) > 1:
return False
return True
n = len(s)
presum = [[0] * 10 for _ in range(n + 1)]
for i, c in enumerate(s):
presum[i + 1][int(c)] += 1
for j in range(10):
presum[i + 1][j] += presum[i][j]
vis = set(s[i : j + 1] for i in range(n) for j in range(i, n) if check(i, j))
return len(vis)