1. Count with ?? 0
Nullish coalescing defaults a missing count to 0 before incrementing.
count.set(ch, (count.get(ch) ?? 0) + 1)Typorithm · medium
Step 1 of 7 · intro card
Sliding Window
Keep a window where (length minus most-frequent count) <= k, since those are exactly the characters you must replace.
With k replacements, a window is valid if all but the most common character can be changed to match it.
That replacement cost is window length minus the highest character frequency.
Expand right, update the frequency, and shrink left whenever the cost exceeds k.
Cost = window length - maxFreq.
Valid while cost <= k.
Shrink left when over budget.
function characterReplacement(s, k) {
const count = new Map();
let left = 0;
let maxFreq = 0;
let best = 0;
for (let right = 0; right < s.length; right += 1) {
const ch = s[right];
count.set(ch, (count.get(ch) ?? 0) + 1);
maxFreq = Math.max(maxFreq, count.get(ch));
while (right - left + 1 - maxFreq > k) {
count.set(s[left], count.get(s[left]) - 1);
left += 1;
}
best = Math.max(best, right - left + 1);
}
return best;
}Connect each part of the code to the concept before you type.
Nullish coalescing defaults a missing count to 0 before incrementing.
count.set(ch, (count.get(ch) ?? 0) + 1)Track the highest single-character frequency in the window.
maxFreq = Math.max(maxFreq, count.get(ch))Window size minus the dominant count is how many chars must change.
while (right - left + 1 - maxFreq > k) {Drop the leftmost character's count as the window shrinks.
count.set(s[left], count.get(s[left]) - 1)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.