BackmediumSliding Window Uber

Character Replacement Solution

Problem Statement

Given a string s and an integer k, find the length of the longest substring that can be replaced with at most k different characters.

Example 1
Input
s = "ABBBCC", k = 2
Output
3

Explanation: Step-by-step: with input s = "ABBBCC" and k = 2, we initialize two pointers at the start of the string. We then iterate over the string, expanding the window to the right. When we encounter a character that is different from the character at the left pointer, we increment the count of different characters. If the count exceeds k, we move the left pointer to the right until the count is less than or equal to k. The maximum length of the substring with at most k different characters is then the maximum length of the window. In this case, the longest substring with at most 2 different characters is 'BBB' and 'CCC' which has a length of 3.

Example 2
Input
s = "ABC", k = 1
Output
1

Explanation: Step-by-step: with input s = "ABC" and k = 1, we initialize two pointers at the start of the string. We then iterate over the string, expanding the window to the right. When we encounter a character that is different from the character at the left pointer, we increment the count of different characters. If the count exceeds k, we move the left pointer to the right until the count is less than or equal to k. The maximum length of the substring with at most k different characters is then the maximum length of the window. In this case, the longest substring with at most 1 different character is 'A' or 'B' or 'C' which has a length of 1.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of uppercase English letters
  • 0 <= k <= s.length
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free