MediumNo. 2168LeetCode Premium
Unique Substrings With Equal Digit Frequency — LeetCode 2168 Python Solution
- Pattern
- Hash Map
- Topics
- Hash Table, String, Counting, Hash Function, Rolling Hash
- Reading time
- 4 min
- Source
- leetcode.com
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
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
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0187 | Repeated DNA Sequences | Medium |
| 1461 | Check If a String Contains All Binary Codes of Size K | Medium |
| 0299 | Bulls and Cows | Medium |
| 0383 | Ransom Note | Easy |
| 0387 | First Unique Character in a String | Easy |
| 0451 | Sort Characters By Frequency | Medium |
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.