Repaint the Fence

Mediumsliding windowAlso known as Longest Repeating Character Replacement

A long garden fence has boards painted in different colours over the years. Each colour is a capital letter, so the fence reads like "GGRGBBG".

An artist wants an unbroken one-colour stretch as a mural background. She has paint for only k boards, and can repaint a board any colour. How long a one-colour stretch can she make?

Your task

Write longestOneColour(boards, k). You may change at most k characters of boards, each to any capital letter. Return the length of the longest run of consecutive equal characters you can make.

An empty fence gives 0.

longestOneColour(boards: string, k: int) → int

Examples

Example 1
Input
boards = "GGRGBBG"
k = 1
Output
4
Why

Repaint the R green: the first four boards become GGGG, using the one repaint. GGRGB would need two repaints (the R and the B). The answer is 4.

Example 2
Input
boards = "RBRBRB"
k = 2
Output
5
Why

Repainting the two B's in RBRBR makes RRRRR, length 5. Every 6-board stretch has three of each colour, so it would need three repaints.

Constraints

  • 0 ≤ boards.length ≤ 10,000
  • 0 ≤ k ≤ boards.length
  • boards contains capital letters A-Z only.
Start with brute force

Check every stretch: count its colours, and if length - mostCommon ≤ k, record the length.

A 10,000-board fence has about 50 million stretches. Even updating counts as the end moves, that is O(n²) work, mostly on stretches that are obviously too short or too expensive.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code