Skip to content

Commit

Permalink
Sync LeetCode submission Runtime - 1093 ms (80.64%), Memory - 18.5 MB…
Browse files Browse the repository at this point in the history
… (49.46%)
  • Loading branch information
jimit105 committed Jan 8, 2025
1 parent 2436a75 commit 2fba83d
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
26 changes: 26 additions & 0 deletions 2303-unique-substrings-with-equal-digit-frequency/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
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>
<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;1212&quot;
<strong>Output:</strong> 5
<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;.
Note that although the substring &quot;12&quot; appears twice, it is only counted once.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;12321&quot;
<strong>Output:</strong> 9
<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;.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
<li><code>1 &lt;= s.length &lt;= 1000</code></li>
<li><code>s</code> consists of digits.</li>
</ul>
37 changes: 37 additions & 0 deletions 2303-unique-substrings-with-equal-digit-frequency/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Approach 1: Optimized Brute Force

# Time: O(n^3)
# Space: O(n^3)

class Solution:
def equalDigitFrequency(self, s: str) -> int:
n = len(s)
valid_substrings = set()

for start in range(n):
digit_freq = [0] * 10 # Frequency array for digits 0-9

for end in range(start, n):
digit_freq[ord(s[end]) - ord('0')] += 1

# Variable to store the frequency all digits must match
common_freq = 0
is_valid = True

for count in digit_freq:
if count == 0:
continue # Skip digits not in the substring
if common_freq == 0:
# First digit found, set common_frequency
common_freq = count
if common_freq != count:
# Mismatch in frequency, mark as invalid
is_valid = False
break

if is_valid:
substring = s[start : end + 1]
valid_substrings.add(substring)

return len(valid_substrings)

0 comments on commit 2fba83d

Please sign in to comment.