Longest Repeating Substring After ReplacementsLoading saved progress…

Longest Repeating Substring After Replacements

You're given a string s and a budget k. You may replace at most k characters in s with any other letters. After those replacements, what is the length of the longest run of a single repeated character you can produce? You don't have to return the substring itself — just its length. Think of it as a contiguous stretch of the string where, by spending up to k swaps, every character becomes the same letter.

Signature

// s: string  — the input (assume uppercase A–Z letters)
// k: number  — the maximum number of characters you may replace (k >= 0)
// returns: number — the length of the longest substring that becomes
//                   a single repeated character after at most k replacements
function longestRepeatingSubstringAfterReplacements(s, k): number;

The substring must be contiguous — you pick a start and end index, and within that window you replace up to k characters so the whole window is one letter.

Examples

// Replace both 'B's with 'A' (or both 'A's with 'B') → "AAAA" or "BBBB", length 4.
longestRepeatingSubstringAfterReplacements('ABAB', 2); // → 4
// Window "BABB" (indices 2–5): replace the one 'A' at index 3 with 'B' to get
// "BBBB" using one swap. Length 4. No valid window of length 5 exists for k=1.
longestRepeatingSubstringAfterReplacements('AABABBA', 1); // → 4
// With no replacements allowed, you can only use a run that already exists.
// The longest existing run of one character is "BBB", length 3.
longestRepeatingSubstringAfterReplacements('AABBBCC', 0); // → 3
// Every character is already the same — no swaps needed, the whole string counts.
longestRepeatingSubstringAfterReplacements('BBBBBB', 2); // → 6

Notes

  • Uppercase letters assumed. The input contains only AZ. You don't need to handle lowercase, digits, or other characters — though the sliding-window approach generalizes to any alphabet (see the solution's Going further).
  • At most k replacements, not exactly k. If a window is already uniform you spend zero swaps; you never have to use the full budget.
  • k can be 0. With no swaps allowed, the answer is the longest run of a single repeated character that already exists in s.
  • Empty string returns 0. No window, no length.
  • You return a length, not the substring. A single number.
  • k may exceed the string length. If your budget is at least the length of s, you can turn the entire string into one letter — the answer is s.length.
Loading editor…