FastPrepLongest Repeating Character Replacement
Problem · String

Longest Repeating Character Replacement

Learn this problem
MediumDigitalOcean logoDigitalOceanFULLTIMEONSITE INTERVIEW

Problem statement

Given a string s and an integer k, you may replace at most k characters with other uppercase English letters. Return the maximum length of a contiguous substring that can contain only one repeated character after these replacements.

For this exercise, assume the input contains only uppercase English letters. Return 0 for an empty string; replacements may be unused.

Function

characterReplacement(s: String, k: int) → int

Examples

Example 1

s = "ABAB"k = 2return = 4

Replace both B characters to obtain AAAA.

Example 2

s = "AABABBA"k = 1return = 4

The first four characters AABA can become AAAA with one replacement. Every length-five window needs at least two.

Example 3

s = ""k = 0return = 0

An empty string has length zero.

Constraints

  • 0 <= s.length <= 10^5.
  • 0 <= k <= s.length.
  • Every character is between A and Z.

More DigitalOcean problems

drafts saved locally
public int characterReplacement(String s, int k) {
    // Write your code here.
}
s"ABAB"
k2
expected4
checking account