- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 39 lines of Python from the credited upstream file 2168.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def equalDigitFrequency(self, s: str) -> int:3 BASE = 114 HASH = 1_000_000_0075 counts: list[dict] = [] 6 count = collections.Counter()7 pows = [1] 8 9 10 hash = [0]11 12 def val(c: str) -> int:13 return int(c) + 114 15 for c in s:16 count[c] += 117 counts.append(count.copy())18 pows.append(pows[-1] * BASE % HASH)19 hash.append((hash[-1] * BASE + val(c)) % HASH)20 21 def getRollingHash(l: int, r: int) -> int:22 """Returns the rolling hash of s[l..r)."""23 h = (hash[r] - hash[l] * pows[r - l]) % HASH24 return h + HASH if h < 0 else h25 26 return len({getRollingHash(i, j + 1)27 for i in range(len(s))28 for j in range(i, len(s))29 if self._isSameFreq(counts, i, j)})30 31 def _isSameFreq(self, counts: list[dict], i: int, j: int) -> bool:32 count = counts[j].copy()33 if i > 0:34 for c, freq in counts[i - 1].items():35 count[c] -= freq36 if count[c] == 0:37 del count[c]38 return min(count.values()) == max(count.values())39