Skip to content

Commit f137beb

Browse files
Add 'Longest Substring with At Most K Distinct Characters'
1 parent f72cb60 commit f137beb

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ A collection of LeetCode solutions
4242

4343
[Longest Repeating Character Replacement](./src/longest_repeating_character_replacement.py)
4444

45+
[Longest Substring with At Most K Distinct Characters](./src/longest_substring_with_at_most_k_distinct_characters.py)
46+
4547
[Longest Substring with At Most Two Distinct Characters](./src/longest_substring_with_at_most_two_distinct_characters.py)
4648

4749
[Longest Substring Without Repeating Characters](./src/test_longest_substring_without_repeating_characters.py)
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
340. Longest Substring with At Most K Distinct Characters
3+
4+
https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters
5+
6+
NOTES
7+
* Use a sliding window.
8+
9+
A general solution to 'Longest Substring with At Most Two Distinct Characters'.
10+
Simply substitute 'k' for '2'. Easy bag.
11+
"""
12+
13+
class Solution:
14+
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
15+
left, right, maximum_size = 0, 0, 0
16+
17+
# Maintain a mapping of character -> index of last occurrence.
18+
d: dict[str, int] = {}
19+
20+
while right < len(s):
21+
d[s[right]] = right
22+
23+
# If the map ever contains more than 'k' keys, then the substring
24+
# contains more than 'k' distinct characters.
25+
if len(d) > k:
26+
# Move `left` to the character after the next index.
27+
next_index = min(d.values())
28+
left = next_index + 1
29+
# Remove the character from the hash map.
30+
del d[s[next_index]]
31+
32+
maximum_size = max(maximum_size, right - left + 1)
33+
right += 1
34+
35+
return maximum_size
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""
2+
340. Longest Substring with At Most K Distinct Characters
3+
4+
https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters
5+
"""
6+
7+
from unittest import TestCase
8+
9+
from src.longest_substring_with_at_most_k_distinct_characters import (
10+
Solution,
11+
)
12+
13+
14+
class TestSolution(TestCase):
15+
def test_1(self):
16+
exp = 3
17+
assert Solution().lengthOfLongestSubstringKDistinct("eceba", 2) == exp
18+
19+
def test_2(self):
20+
exp = 2
21+
assert Solution().lengthOfLongestSubstringKDistinct("aa", 1) == exp

0 commit comments

Comments
 (0)