Skip to content

Commit 7d0e187

Browse files
Add solution for 'longest repeating character replacement'
Implement a sliding window approach for solving the problem, ensuring efficient handling of character replacement within a string. Included unit tests to validate functionality and edge cases.
1 parent a6321cf commit 7d0e187

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# https://neetcode.io/problems/longest-repeating-substring-with-replacement
2+
3+
import unittest
4+
5+
from collections import Counter
6+
7+
def character_replacement(s: str, k: int) -> int:
8+
counts = Counter(s)
9+
10+
left = 0
11+
result = 0
12+
13+
for right, char in enumerate(s):
14+
# Shrink the window when the current window size minus the count of the most
15+
# frequent character in the window exceeds k. This means we have more characters
16+
# to replace than allowed by k, so we need to move the left pointer to reduce
17+
# the window size.
18+
19+
while (right - left + 1) - counts[char] > k:
20+
left += 1
21+
22+
result = max(result, right - left + 1)
23+
24+
return result
25+
26+
class Test(unittest.TestCase):
27+
def test_character_replacement(self):
28+
self.assertEqual(character_replacement("XYYX", 2), 4)
29+
self.assertEqual(character_replacement("AAABABB", 1), 5)

0 commit comments

Comments
 (0)