Skip to content
Algorithms for Beginners

Problems / Sliding window

Repaint the fence

medium

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

A fence is a row of boards, each painted a colour. fence describes it, one capital letter per board: "ABAB" is four boards, alternating colours A and B.

You can repaint at most k boards, each to any colour. Return the length of the longest stretch of boards in a row that can end up all the same colour.

Examples

  1. Example 1

    Input
    fence = "XYXY", k = 2
    Output
    4

    Repaint both X's to Y (or both Y's to X): all 4 boards match.

  2. Example 2

    Input
    fence = "CABCCAC", k = 1
    Output
    4

    Boards 3 to 6 are "CCAC". Repaint the A and they're all C.

  3. Example 3

    Input
    fence = "XYZ", k = 0
    Output
    1

    No repaints allowed, and no two neighbours match.

Rules

  • fence has between 0 and 100,000 boards, each a capital letter A to Z.
  • k is between 0 and the number of boards.
Words on this page, in plain English (1)Open if any word is new to you
Length
How many items a list (or letters a string) has. The last position is always length - 1.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function repaintStretch(fence, k) {
  // Return the longest stretch that can be one colour.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in sliding window

  • Learn the sliding window pattern

    Keep a stretch of the list and slide it along instead of starting over.

  • Hidden shuffle

    Medium. Check whether some rearrangement of a short word appears inside a longer text.

  • Two kinds

    Medium. Find the longest stretch of a list that contains at most two different values.

  • Best streak

    Easy. Find the highest total of any k days in a row.

  • Longest unique stretch

    Medium. Find the longest stretch of text in which no character repeats.

  • Shortest to target

    Medium. Find the fewest days in a row whose rainfall adds up to at least a target.