Paths Subjects Questions Quizzes Pricing Search
Advanced Open Pro

Longest Uniform Substring After Replacements

Given a string s consisting of uppercase English letters and an integer k, you may replace up to k characters of s with any other uppercase English letter. Return the length of the longest substring you can make consist of a single repeated character after performing at most k such replacements.

Example 1:

Input: s = "ABAB", k = 2
Output: 4
Explanation: Replace the two 'A's or the two 'B's with the other
letter to get "BBBB" or "AAAA", both of length 4.

Example 2:

Input: s = "AABABBA", k = 1
Output: 4
Explanation: Replace one 'A' inside "ABBA" (the substring
s[1..4] = "ABBA") to get "BBBA", or similar, giving a uniform run of
length 4. Note that after the replacement the surrounding characters
may no longer be part of one uniform substring, and the string
itself is not fully uniform, but a window of length 4 can be made
uniform.

Constraints:

  • 1 <= s.length <= 5 * 10^4
  • s consists only of uppercase English letters.
  • 0 <= k <= s.length

Hint: for a window [left, right] of length L containing some character with the highest frequency maxFreq inside that window, the window can be made uniform with L - maxFreq replacements (replace every character that is not the majority character).

Share this question

← Back to Sliding Windows practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.