Sliding Window Longest or shortest window

172. Longest Repeating Character Replacement

Medium 147 DSA Sheet

You are given a string s of uppercase letters and an integer k. You may change at most k letters of s. Each change replaces one letter with any uppercase letter you like.

After the changes, find the longest substring in which every letter is the same. Return its length.

A substring is a block of letters that sit next to each other in s. The changed letters can be anywhere in the string, and they count toward the length like any other letter.

Example 1

Input: s = "CABBACBB", k = 2

Output: 6

Explanation: Take the last six letters, BBACBB. Change the A and the C to B, and they read BBBBBB. A block of seven would need five copies of one letter, and no block of seven holds more than four.

Example 2

Input: s = "AABBBA", k = 0

Output: 3

Explanation: With no changes allowed, the answer is the longest block of one letter as it stands, BBB.

Example 3

Input: s = "MNOP", k = 3

Output: 4

Explanation: Every letter is different. Change any three of them to the fourth, and the whole string is one letter.

Check your understanding

Work out the answer for this input before you write any code.

s = "BANANA", k = 2

Constraints

  • 1 ≤ s.length ≤ 105
  • s holds uppercase English letters only, A to Z.
  • 0 ≤ k ≤ s.length

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.