Skip to content

Commit f79c7f3

Browse files
committed
Sync LeetCode submission Runtime - 11 ms (66.61%), Memory - 17.7 MB (79.05%)
1 parent 7810d50 commit f79c7f3

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the number of substrings in </em><code>s</code><em> of length </em><code>k</code><em> with no repeated characters</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> s = &quot;havefunonleetcode&quot;, k = 5
8+
<strong>Output:</strong> 6
9+
<strong>Explanation:</strong> There are 6 substrings they are: &#39;havef&#39;,&#39;avefu&#39;,&#39;vefun&#39;,&#39;efuno&#39;,&#39;etcod&#39;,&#39;tcode&#39;.
10+
</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> s = &quot;home&quot;, k = 5
16+
<strong>Output:</strong> 0
17+
<strong>Explanation:</strong> Notice k can be larger than the length of s. In this case, it is not possible to find any substring.
18+
</pre>
19+
20+
<p>&nbsp;</p>
21+
<p><strong>Constraints:</strong></p>
22+
23+
<ul>
24+
<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>
25+
<li><code>s</code> consists of lowercase English letters.</li>
26+
<li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li>
27+
</ul>
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Approach 2: Sliding Window
2+
3+
# n = len(s), m = no. of unique chars (i.e. 26)
4+
# Time: O(n)
5+
# Space: O(m) = O(26) = O(1)
6+
7+
class Solution:
8+
def numKLenSubstrNoRepeats(self, s: str, k: int) -> int:
9+
if k > 26:
10+
return 0
11+
answer = 0
12+
n = len(s)
13+
14+
left = right = 0
15+
freq = [0] * 26
16+
17+
def get_val(ch):
18+
return ord(ch) - ord('a')
19+
20+
while right < n:
21+
freq[get_val(s[right])] += 1
22+
23+
while freq[get_val(s[right])] > 1:
24+
freq[get_val(s[left])] -= 1
25+
left += 1
26+
27+
if right - left + 1 == k:
28+
answer += 1
29+
30+
freq[get_val(s[left])] -= 1
31+
left += 1
32+
33+
right += 1
34+
35+
return answer
36+
37+
38+
39+

0 commit comments

Comments
 (0)