Unique Substrings With Equal Digit Frequency — LeetCode 2168 Python Solution

MediumLeetCode PremiumHash TableStringCountingHash FunctionRolling Hash
Problem
#2168
Pattern
Hash Map
Reading time
4 min

The problem

Given a digit string s, return the number of unique substrings of s where every digit appears the same number of times.

Example

Input
s = "1212"
Output
5
Explanation
The substrings that meet the requirements are "1", "2", "12", "21", "1212".

Python solution

Python
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)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2168. Unique Substrings With Equal Digit Frequency is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2168. Unique Substrings With Equal Digit Frequency?
LeetCode 2168. Unique Substrings With Equal Digit Frequency is rated Medium on LeetCode.
What is the time complexity of LeetCode 2168. Unique Substrings With Equal Digit Frequency?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2168. Unique Substrings With Equal Digit Frequency?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2168. Unique Substrings With Equal Digit Frequency cover?
LeetCode 2168. Unique Substrings With Equal Digit Frequency is tagged Hash Table, String, Counting, Hash Function and Rolling Hash on LeetCode.
Is LeetCode 2168. Unique Substrings With Equal Digit Frequency a premium problem?
Yes. LeetCode 2168. Unique Substrings With Equal Digit Frequency is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview