Problems/Sliding Windows/Longest Uniform Substring After Replacements
Sliding Windows
medium

Longest Uniform Substring After Replacements

Find the longest consecutive segment of a string that can be made up of the same character by changing at most 'k' characters. This tests your ability to use sliding windows and optimize for substring problems.

stringsliding windowsubstringoptimizationfrequency counter

Problem Statement

You are given a string 's' consisting of lowercase English letters. You are also given an integer 'k', which represents the maximum number of characters you are allowed to change in the string. Your task is to find the length of the longest substring of 's' that can be made up of only one repeating character after making at most 'k' changes. For example, if 's' is 'ababa' and 'k' is 1, you can change the middle 'b' to 'a' to get 'aaaaa', so the answer is 5.

Example 1
Input: s = 'abcabcbb', k = 2
Output: 5
We can change the last two 'b's to 'c's to get 'abccccc', giving us a uniform substring of length 5 ('ccccc').
Example 2
Input: s = 'aabbccddd', k = 1
Output: 4
We can change the last 'c' to 'd' to get 'aabbcdddd', giving us a uniform substring of length 4 ('dddd').
Constraints
  • -1 <= len(s) <= 10^5
  • -s consists of lowercase English letters
  • -0 <= k <= len(s)

Brute Force Approach

The brute force approach would involve checking every possible substring of the given string. For each substring, we count the frequency of each character and determine if it can be made uniform with at most 'k' changes. Think of it like manually inspecting every possible section of a roll of film to see if it's mostly the same color, and doing that for every single possible section. This approach is very inefficient because we recalculate frequencies for many overlapping substrings. The time complexity would be O(n^2) because we iterate through all possible substrings, and the space complexity would be O(1) because we only use a constant amount of extra space.

TimeO(n^2)
SpaceO(1)

Ready to practice?

Work through this problem with AI coaching and get real-time feedback

Practice This Problem