Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the longest substring after at most K character replacements

Given a string and an integer K, find the length of the longest substring achievable by replacing at most K characters so that all characters in the substring are the same.

Python practice25 minStrings – Sliding Window & FrequencyAdvancedLast updated March 25, 2026

Problem statement

You are given a string s and an integer k. You may choose any substring and replace at most k characters within that substring with any characters you choose. Return the length of the longest substring you can obtain such that all characters in the substring are the same after at most k replacements. Example: s = "AABABBA", k = 1 -> The longest substring length is 4 (we can change one 'A' in "AABA" or one 'B' in "ABBA" to make four identical characters).

Task

Use a sliding window and track the count of the most frequent character in the window to determine if at most K replacements are needed; maintain the maximum window size.

Examples

Example 1

Input

s = "AABABBA", k = 1

Output

4

Replace one character to get "AABA" or "ABBA" where four characters become identical.

Input format

Two inputs: string s and integer k.

Output format

An integer representing the length of the longest substring that can be made all the same character after at most k replacements.

Constraints

- 0 <= len(s) <= 10^5 - 0 <= k <= len(s) - s consists of ASCII characters; solution should be O(n) time and O(1) or O(m) space where m <= charset size.

Samples

Sample 1

Input

s = "AABABBA", k = 1

Output

4

We can replace one character to make a substring of length 4 with all same characters.