Skip to the workspace
Pebellslearn by building
Sliding Window  ›  Capstone Project

Keep the Window Valid: Most Common Plus a Budget

Character Replacement 16 minA stretch can be made uniform with at most k changes when its size minus the count of its most common item is at most k, and a sliding window that keeps this rule true finds the longest such stretch.

leetcode / Keep the Window Valid: Most Common Plus a Budget

Explore each scene at your own pace.

01 · The rule

The rule

Keep the Window Valid: Most Common Plus a Budget

A path is laid with coloured tiles: red, red, green, red, blue, red, red (RRGRBRR). A painter may repaint at most one tile. What is the longest run of same-coloured tiles they can end up with? The window idea from the last lesson still works. The only new skill is writing down, in one line, what makes a window "valid".

The rule

A window is valid when its size minus its most common count fits the budget.

Inside any stretch of tiles, the cheapest way to make them all one colour is to keep the colour that already appears most and repaint the rest. So the repaints needed are size − count of the most common colour. If that number is at most k, the stretch can be made uniform. Everything else is the grow-and-shrink loop, with a dictionary of colour counts as the thing the window tracks:

def longest_after_repaints(tiles, k):
    counts = {}
    left = best = 0
    for right, colour in enumerate(tiles):
        counts[colour] = counts.get(colour, 0) + 1
        while (right - left + 1) - max(counts.values()) > k:   # too many repaints
            counts[tiles[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best

With a handful of colours, max(counts.values()) is quick, so the whole run is one pass. Shrinking is safe for the usual reason: a shorter stretch inside a fixable one never needs more repaints.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.