Repaint the Fence

Mediumsliding windowAlso known as Longest Repeating Character Replacement

A long garden fence is made of boards that neighbours have painted over the years in different colours. Each board's colour is a capital letter, so the fence reads like "GGRGBBG".

An artist wants an unbroken stretch of boards in one single colour as the background for a mural. She only has enough paint for k boards. Repainting a board changes it to any colour she likes. What is the longest one-colour stretch she can end up with?

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. That uses the one repaint. The stretch GGRGB would need two repaints (the R and the B), which is too many. The answer is 4.

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

Take the five boards RBRBR. Repainting the two B's red 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: for each start and end, count the colours, and if length - mostCommon ≤ k, record the length.

There are about 50 million stretches in a 10,000-board fence, and each needs its own counts. Even with counts updated as the end moves, it is O(n²) work, and most stretches are obviously too short or obviously 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