Skip to content

Commit 134937e

Browse files
Optimize sliding window logic to track max character frequency.
Replaced `Counter` with `defaultdict` for efficiency and added a `max_frequency` variable to keep track of the most frequent character in the current window. Updated the window shrinking condition to use `max_frequency`, improving clarity and performance. Added additional test cases for better coverage.
1 parent 7d0e187 commit 134937e

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

Sliding Window/longest_repeating_character_replacement.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,26 @@
22

33
import unittest
44

5-
from collections import Counter
5+
from collections import defaultdict
66

77
def character_replacement(s: str, k: int) -> int:
8-
counts = Counter(s)
8+
counts = defaultdict(int)
99

1010
left = 0
11+
max_frequency = 0 # Track the frequency of the most frequent character in the current window
1112
result = 0
1213

1314
for right, char in enumerate(s):
15+
counts[char] += 1
16+
max_frequency = max(max_frequency, counts[char])
17+
1418
# Shrink the window when the current window size minus the count of the most
1519
# frequent character in the window exceeds k. This means we have more characters
1620
# to replace than allowed by k, so we need to move the left pointer to reduce
1721
# the window size.
1822

19-
while (right - left + 1) - counts[char] > k:
23+
while (right - left + 1) - max_frequency > k:
24+
counts[s[left]] -= 1
2025
left += 1
2126

2227
result = max(result, right - left + 1)
@@ -27,3 +32,5 @@ class Test(unittest.TestCase):
2732
def test_character_replacement(self):
2833
self.assertEqual(character_replacement("XYYX", 2), 4)
2934
self.assertEqual(character_replacement("AAABABB", 1), 5)
35+
self.assertEqual(character_replacement("ABABBA", 2), 5)
36+
self.assertEqual(character_replacement("AABACCC", 2), 5)

0 commit comments

Comments
 (0)