Sliding Window · 15 min · free lesson

Minimum Cover Window: When to Use It

Recognise the problem shape before choosing Minimum Cover Window.

Core idea

Repeated required symbols must each be covered. State the input preconditions before applying this invariant.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Expand until all required multiplicities are covered, then shrink while coverage remains.

O(n) time · O(alphabet) space129 execution steps
main · before line 37Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputADOBECODEBANC

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 37
fn minimum_cover<'a>(text: &'a str, required: &str) -> &'a str {
    assert!(text.is_ascii() && required.is_ascii());
    if required.is_empty() {
        return "";
    }
    let mut need = [0_i32; 256];
    for c in required.bytes() {
        need[c as usize] += 1;
    }
    let (mut missing, mut left) = (required.len(), 0);
    let mut best = (0, usize::MAX);
    for (right, c) in text.bytes().enumerate() {
        if need[c as usize] > 0 {
            missing -= 1;
        }
        need[c as usize] -= 1;
        while missing == 0 {
            if right + 1 - left < best.1 {
                best = (left, right + 1 - left);
            }
            let old = text.as_bytes()[left] as usize;
            need[old] += 1;
            left += 1;
            if need[old] > 0 {
                missing += 1;
            }
        }
    }
    if best.1 == usize::MAX {
        ""
    } else {
        &text[best.0..best.0 + best.1]
    }
}
 
fn main() {
    let result = minimum_cover("ADOBECODEBANC", "ABC").to_string();
    println!("{result}");
}

Try your own version

Compare the visible input `ADOBECODEBANC` with `CBA`. Predict why their results are `BANC` and `CBA`. Then change one legal value and explain whether the same invariant, repeated required symbols must each be covered, still applies.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Sliding Window infographic; panel 2 illustrates Minimum Cover Window.
Minimum Cover Window: follow panel 2 to see the operation, then trace this lesson's example.

Understand it

In ADOBECODEBANC, an early valid cover contains unnecessary symbols and can shrink. The final BANC contains A, B and C in length 4. A valid cover may contain extra symbols; remove them only while all required counts remain satisfied.

The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: For ASCII text, return the shortest substring covering A, B and C; choose the earliest if lengths tie, or the empty string if no cover exists. The visible fixture is ADOBECODEBANC and its example result is BANC. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.

Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.

String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

A problem is a good match for Minimum Cover Window when it asks for smallest substring or range containing a multiset. Here the concrete task is: For ASCII text, return the shortest substring covering A, B and C; choose the earliest if lengths tie, or the empty string if no cover exists. The visible input ADOBECODEBANC is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Choose this family when a valid window can be repaired by moving one boundary; non-monotone constraints may need a different method. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Expand until all required multiplicities are covered, then shrink while coverage remains. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? A window is a contiguous interval with a maintained summary. Describe what entering the right edge adds and what leaving the left edge removes. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.

Compare costs before committing. The advertised bound is O(n) time · O(alphabet) space; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict BANC and explain which part of the state lets the method reach that result.

When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Test an empty window, a window spanning the whole input, and a case where the left edge must advance several times. Represent bounds as a half-open range when possible. Keep counts and the window length in sync when shrinking it. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.

The pattern

Expand until all required multiplicities are covered, then shrink while coverage remains.

When to use it: smallest substring or range containing a multiset

Complexity: O(n) time · O(alphabet) space

Input: ADOBECODEBANC

Read the code

fn minimum_cover<'a>(text: &'a str, required: &str) -> &'a str {
    assert!(text.is_ascii() && required.is_ascii());
    if required.is_empty() {
        return "";
    }
    let mut need = [0_i32; 256];
    for c in required.bytes() {
        need[c as usize] += 1;
    }
    let (mut missing, mut left) = (required.len(), 0);
    let mut best = (0, usize::MAX);
    for (right, c) in text.bytes().enumerate() {
        if need[c as usize] > 0 {
            missing -= 1;
        }
        need[c as usize] -= 1;
        while missing == 0 {
            if right + 1 - left < best.1 {
                best = (left, right + 1 - left);
            }
            let old = text.as_bytes()[left] as usize;
            need[old] += 1;
            left += 1;
            if need[old] > 0 {
                missing += 1;
            }
        }
    }
    if best.1 == usize::MAX {
        ""
    } else {
        &text[best.0..best.0 + best.1]
    }
}

fn main() {
    let result = minimum_cover("ADOBECODEBANC", "ABC").to_string();
    println!("{result}");
}

Complete std-only minimum-cover-window program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Try it

Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.

What success looks like: You can justify the choice from constraints rather than from a remembered problem title.

Check your understanding

Trace Minimum Cover Window on input AAABBC. Which result follows from the documented contract?

Reveal the answer
  1. AAABBC
  2. ABBC
  3. BBC

For this input the result is ABBC. Repeated required symbols must each be covered. Compare this independent fixture with the worked trace: In ADOBECODEBANC, an early valid cover contains unnecessary symbols and can shrink. The final BANC contains A, B and C in length 4. A valid cover may contain extra symbols; remove them only while all required counts remain satisfied.

Go deeper

Common misconception: “Every target is implicitly a set”

Repeated required symbols must each be covered. In ADOBECODEBANC, an early valid cover contains unnecessary symbols and can shrink. The final BANC contains A, B and C in length 4. A valid cover may contain extra symbols; remove them only while all required counts remain satisfied.

  1. Concrete transition: In ADOBECODEBANC, an early valid cover contains unnecessary symbols and can shrink. The final BANC contains A, B and C in length 4. A valid cover may contain extra symbols; remove them only while all required counts remain satisfied.
  2. Independent second fixture: Input AAABBC produces ABBC. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input CABAC produces CAB. Repeated required symbols must each be covered. The stated work bound is O(n) time · O(alphabet) space. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input ADOBECODEBANC with CBA. Predict why their results are BANC and CBA. Then change one legal value and explain whether the same invariant, repeated required symbols must each be covered, still applies.

Connections

  • Minimum Cover Window: Mental Model: Expand until all required multiplicities are covered, then shrink while coverage remains.
  • Challenge: Minimum Cover Window: For ASCII text, return the shortest substring covering A, B and C; choose the earliest if lengths tie, or the empty string if no cover exists.
Reveal the Algorithm Atlas answer

BANC

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Minimum Cover Window: When to Use It (courseId "algorithms", lessonId "algorithm.minimum-cover-window.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.minimum-cover-window.recognize
Goal: Repeated required symbols must each be covered. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.minimum-cover-window.recognize) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.