Skip to content

Commit b46f3fd

Browse files
committed
Sync LeetCode submission Runtime - 368 ms (7.91%), Memory - 17.9 MB (39.71%)
1 parent 37dfb15 commit b46f3fd

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<p>Given a string <code>s</code>&nbsp;consisting only of characters <em>a</em>, <em>b</em> and <em>c</em>.</p>
2+
3+
<p>Return the number of substrings containing <b>at least</b>&nbsp;one occurrence of all these characters <em>a</em>, <em>b</em> and <em>c</em>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> s = &quot;abcabc&quot;
10+
<strong>Output:</strong> 10
11+
<strong>Explanation:</strong> The substrings containing&nbsp;at least&nbsp;one occurrence of the characters&nbsp;<em>a</em>,&nbsp;<em>b</em>&nbsp;and&nbsp;<em>c are &quot;</em>abc<em>&quot;, &quot;</em>abca<em>&quot;, &quot;</em>abcab<em>&quot;, &quot;</em>abcabc<em>&quot;, &quot;</em>bca<em>&quot;, &quot;</em>bcab<em>&quot;, &quot;</em>bcabc<em>&quot;, &quot;</em>cab<em>&quot;, &quot;</em>cabc<em>&quot; </em>and<em> &quot;</em>abc<em>&quot; </em>(<strong>again</strong>)<em>. </em>
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> s = &quot;aaacb&quot;
18+
<strong>Output:</strong> 3
19+
<strong>Explanation:</strong> The substrings containing&nbsp;at least&nbsp;one occurrence of the characters&nbsp;<em>a</em>,&nbsp;<em>b</em>&nbsp;and&nbsp;<em>c are &quot;</em>aaacb<em>&quot;, &quot;</em>aacb<em>&quot; </em>and<em> &quot;</em>acb<em>&quot;.</em><em> </em>
20+
</pre>
21+
22+
<p><strong class="example">Example 3:</strong></p>
23+
24+
<pre>
25+
<strong>Input:</strong> s = &quot;abc&quot;
26+
<strong>Output:</strong> 1
27+
</pre>
28+
29+
<p>&nbsp;</p>
30+
<p><strong>Constraints:</strong></p>
31+
32+
<ul>
33+
<li><code>3 &lt;= s.length &lt;= 5 x 10^4</code></li>
34+
<li><code>s</code>&nbsp;only consists of&nbsp;<em>a</em>, <em>b</em> or <em>c&nbsp;</em>characters.</li>
35+
</ul>
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Approach 1: Sliding Window
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def numberOfSubstrings(self, s: str) -> int:
8+
left = right = total = 0
9+
freq = [0] * 3
10+
11+
while right < len(s):
12+
freq[ord(s[right]) - ord('a')] += 1
13+
14+
while self._has_all_chars(freq):
15+
# All substrings from current window to end are valid
16+
# Add count of valid substrings
17+
total += len(s) - right
18+
19+
# Remove leftmost character and move left pointer
20+
freq[ord(s[left]) - ord('a')] -= 1
21+
left += 1
22+
23+
right += 1
24+
25+
return total
26+
27+
def _has_all_chars(self, freq):
28+
return all(f > 0 for f in freq)
29+
30+
31+

0 commit comments

Comments
 (0)