Skip to content

Commit 2fba83d

Browse files
committed
Sync LeetCode submission Runtime - 1093 ms (80.64%), Memory - 18.5 MB (49.46%)
1 parent 2436a75 commit 2fba83d

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
Given a digit string <code>s</code>, return <em>the number of <strong>unique substrings </strong>of </em><code>s</code><em> where every digit appears the same number of times.</em>
2+
<p>&nbsp;</p>
3+
<p><strong class="example">Example 1:</strong></p>
4+
5+
<pre>
6+
<strong>Input:</strong> s = &quot;1212&quot;
7+
<strong>Output:</strong> 5
8+
<strong>Explanation:</strong> The substrings that meet the requirements are &quot;1&quot;, &quot;2&quot;, &quot;12&quot;, &quot;21&quot;, &quot;1212&quot;.
9+
Note that although the substring &quot;12&quot; appears twice, it is only counted once.
10+
</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> s = &quot;12321&quot;
16+
<strong>Output:</strong> 9
17+
<strong>Explanation:</strong> The substrings that meet the requirements are &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;12&quot;, &quot;23&quot;, &quot;32&quot;, &quot;21&quot;, &quot;123&quot;, &quot;321&quot;.
18+
</pre>
19+
20+
<p>&nbsp;</p>
21+
<p><strong>Constraints:</strong></p>
22+
23+
<ul>
24+
<li><code>1 &lt;= s.length &lt;= 1000</code></li>
25+
<li><code>s</code> consists of digits.</li>
26+
</ul>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Approach 1: Optimized Brute Force
2+
3+
# Time: O(n^3)
4+
# Space: O(n^3)
5+
6+
class Solution:
7+
def equalDigitFrequency(self, s: str) -> int:
8+
n = len(s)
9+
valid_substrings = set()
10+
11+
for start in range(n):
12+
digit_freq = [0] * 10 # Frequency array for digits 0-9
13+
14+
for end in range(start, n):
15+
digit_freq[ord(s[end]) - ord('0')] += 1
16+
17+
# Variable to store the frequency all digits must match
18+
common_freq = 0
19+
is_valid = True
20+
21+
for count in digit_freq:
22+
if count == 0:
23+
continue # Skip digits not in the substring
24+
if common_freq == 0:
25+
# First digit found, set common_frequency
26+
common_freq = count
27+
if common_freq != count:
28+
# Mismatch in frequency, mark as invalid
29+
is_valid = False
30+
break
31+
32+
if is_valid:
33+
substring = s[start : end + 1]
34+
valid_substrings.add(substring)
35+
36+
return len(valid_substrings)
37+

0 commit comments

Comments
 (0)