Longest Repeating Character Replacement

Asked byGoogleAmazonUberAdobe

Problem

Given a string s consisting of uppercase letters and an integer k, you may change up to k characters in the string to any other uppercase letter. Return the length of the longest substring containing a single repeated letter you can obtain after performing these changes.

Examples

Example 1
Input:s = "ABAB", k = 2
Output:4
Example 2
Input:s = "AABABBA", k = 1
Output:4

Constraints

  • 1 <= s.length <= 10^5
  • 0 <= k <= s.length

Solve it in the editor. Sign in free to run your Python or JavaScript against test cases, get a verdict, and track your attempts.

Solve on FeatCode →

How to approach it: the Sliding Window pattern

A window — a contiguous subarray or substring — expands and shrinks as it moves across the input, so you track a running condition instead of recomputing it from scratch for every possible window.

Look for this pattern when

  • The problem asks for the longest/shortest/best contiguous subarray or substring meeting a condition.
  • Brute force would recompute a sum or count for every possible window — a sign that work can be shared between overlapping ranges.

Read the full Sliding Window guide →

Video walkthroughs

Original problem on LeetCode ↗

More Sliding Window problems