Frequency-count sliding window

Fit a Letter-Budget Banner

01. The question

A sign maker can stock at most k distinct lowercase letter stamps. Return the longest continuous piece of a message that fits that budget. Repeated letters are allowed. If lengths tie, keep the earliest piece.

Before revealing the idea, predict the result and describe what information you would need to track.

02. Worked example

Inputmessage = "abaccc", k = 2

Output"accc"

  1. "aba" uses only a and b.
  2. Adding c introduces a third letter. Remove letters from the left until b disappears.
  3. The final piece "accc" has four characters but only two distinct letters.

Try your code

Define solve(data, parameter="") and return your result. Your code runs locally, not on a server.

Edit your test cases

Use 1-10 objects with data and an optional string parameter. Expected outputs are computed from the lesson. An optional expected field must be correct.

Input contract & reference code

Example data: "abaccc". Parameter: "2". Numeric parameters arrive as strings; convert them with int(parameter) when needed.

The example and generated cases use the question’s exact variant. This checks behavior on a small test batch—not performance on every possible input.

Python runtime notices

Python downloads only when you run code, using compressed runtime assets. Code is not saved or uploaded. Enable JavaScript to run it.

Five-second execution limit per batch. Standard-library Python only; additional packages and network access are unavailable. Stop ends execution without blocking the lesson.

03. The idea

Try sketching your own approach first. What would you track, and why would it work?

Reveal the idea
  1. Count each letter in the current window.
  2. While too many distinct letters remain, remove the leftmost letter and delete zero counts.
  3. Save the valid window only when it is strictly longer than the best.

04. Watch it happen

Use Step to move slowly, or Play to follow the whole trace. Change a preset or load your own input.

Input & settings

Up to 40 lowercase a-z letters. k: 1-26. Repeats are allowed; ties keep the earliest piece.

Red = current item / blue = active window or cells / green = completed work. A value docks at its actual destination; the original input stays unchanged. Positions start at 0.

Working state / what changes

Ready to begin

Enable JavaScript to step through the animation. The worked example and solution below remain readable without it.

Python / why it changes

The line behind the step

def budget_banner(message, k):
    counts = {}
    left = best_start = best_length = 0
    for right, letter in enumerate(message):
        counts[letter] = counts.get(letter, 0) + 1
        while len(counts) > k:
            outgoing = message[left]
            counts[outgoing] -= 1
            if counts[outgoing] == 0:
                del counts[outgoing]
            left += 1
        length = right - left + 1
        if length > best_length:
            best_start, best_length = left, length
    return message[best_start:best_start + best_length]
How to use this walkthrough

Hover or focus a control for its label. Play forms the input and follows values into the working state. Step shows one change; Back and the slider restore exact snapshots. Reduced motion uses instant updates. Saved snapshots and sorted heap displays are teaching overhead, not algorithm complexity.

05. Python solution

def budget_banner(message, k):
    counts = {}
    left = best_start = best_length = 0
    for right, letter in enumerate(message):
        counts[letter] = counts.get(letter, 0) + 1
        while len(counts) > k:
            outgoing = message[left]
            counts[outgoing] -= 1
            if counts[outgoing] == 0:
                del counts[outgoing]
            left += 1
        length = right - left + 1
        if length > best_length:
            best_start, best_length = left, length
    return message[best_start:best_start + best_length]

06. Cost & edge cases

Time
O(n) expected
Space
O(min(n, alphabet size))
  • k must be 1-26; an empty message returns "".
  • One stamp can print many repeated copies of the same letter.
  • Equal-length pieces keep the earlier one.

Keep going