Skip to content

Commit c69615e

Browse files
committed
sliding window problems
1 parent f78f068 commit c69615e

4 files changed

+65
-0
lines changed

longest_repeat_char_replace.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class LongestRepeatCharReplace():
2+
def longest_repeat_char_replace(self, str: str, k: int) -> int:
3+
count = {}
4+
res = 0
5+
left = 0
6+
maxF = 0
7+
# basically trying to find the longest repeating substring but k values can be different
8+
for right in range(len(str)):
9+
# dict counting freq of characters
10+
count[str[right]] = 1 + count.get(str[right], 0)
11+
maxF = max(maxF, count[str[right]])
12+
# (right - left + 1) - maxF is the # of characters that need to be replaced
13+
while (right - left + 1) - maxF > k:
14+
# start decrementing frequencies of characters as left index starts moving
15+
count[str[left]] -= 1
16+
left += 1
17+
res = max(res, right - left + 1)
18+
return res

longest_repeat_char_replace_test.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# https://leetcode.com/problems/longest-repeating-character-replacement/
2+
from longest_repeat_char_replace import LongestRepeatCharReplace
3+
4+
tester = LongestRepeatCharReplace()
5+
6+
7+
def test_general_case_one():
8+
assert tester.longest_repeat_char_replace("abab", 2) == 4
9+
10+
11+
def test_replace_one():
12+
assert tester.longest_repeat_char_replace("aababba", 1) == 4
13+
14+
15+
def test_no_replacements():
16+
assert tester.longest_repeat_char_replace("pwwkew", 0) == 2

longest_substring_no_repeat.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# https://leetcode.com/problems/longest-substring-without-repeating-characters/
2+
class LongestSubstringNoRepeat():
3+
def longest_substring_no_repeat(self, str: str) -> int:
4+
charSet = set() # {} is dict
5+
max_length = 0
6+
left = 0
7+
for curr in range(len(str)):
8+
# repeat (removing char at left index and incrementing) until val at curr index is not in set
9+
while str[curr] in charSet:
10+
charSet.remove(str[left])
11+
left += 1
12+
charSet.add(str[curr])
13+
max_length = max(max_length, curr - left + 1)
14+
return max_length

longest_substring_no_repeat_test.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# https://leetcode.com/problems/longest-substring-without-repeating-characters/
2+
3+
from longest_substring_no_repeat import LongestSubstringNoRepeat
4+
5+
tester = LongestSubstringNoRepeat()
6+
7+
8+
def test_general_case():
9+
assert tester.longest_substring_no_repeat("abcabcbb") == 3
10+
11+
12+
def test_single_letter():
13+
assert tester.longest_substring_no_repeat("bbbbb") == 1
14+
15+
16+
def test_advance_left_by_two():
17+
assert tester.longest_substring_no_repeat("pwwkew") == 3

0 commit comments

Comments
 (0)