Java String Program · S36
Longest Repeating Character Replacement in Java
You may change up to k letters. How long can a block of identical letters get? A sliding window that tracks its most common letter answers this in one pass.
Problem Statement
Given a string of uppercase English letters and an integer k, you may replace at most k characters with any other uppercase letter.
Return the length of the longest substring that can be made of one repeated letter. The replacements do not have to be used.
Input/Output Examples
"ABBBCA", k = 1Output4Explanation: change C to B in "BBBC" to get "BBBB"."AAAA", k = 2Output4Explanation: the whole string is one letter; no change is needed."ABCDE", k = 1Output2Explanation: any two neighbours can be made equal with one change.Visual Explanation
- right = 3windowABBBlen 4, top B:3 4 − 3 = 1 ≤ k
- right = 4windowABBBClen 5, top 3: 2 > k shrink: drop A
- After shrinkwindowBBBClen 4, top B:3 4 − 3 = 1 ≤ k
- Doneright = 5 does not beat it4
"ABBBCA" with k = 1: a window is valid when its length minus the count of its most common letter is at most k. Adding C breaks the rule, so A leaves from the left.The letters that are not the most common one are exactly the letters that must be replaced. Keeping that number at or below k is the only condition the window has to satisfy.
Approaches
The first approach handles all letters in one window. The second runs a simpler window once for each possible target letter.
Approach 1: Sliding Window With Max Count (Recommended)
Idea: expand the window to the right; shrink it from the left whenever length - maxCount > k.
- Add the character at
rightand updatemaxCount. - While the window needs more than
kreplacements, remove the character atleft. - Record the window length as a candidate answer.
Time: O(n) · Space: O(1).
Approach 2: One Target Letter at a Time
Idea: for each letter A to Z, find the longest window that contains at most k other letters.
- Pick a target letter.
- Slide a window, counting characters that are not the target.
- Shrink while that count exceeds
k, and track the best length. - Repeat for all 26 letters.
Time: O(26 × n) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Sliding Window With Max Count (Recommended)
maxCount is never decreased when the window shrinks. That is safe: a smaller stale value could only make the window look valid when it is not longer than the best already found.
public class ReplacementWindow {
// A window is valid when (window length - count of its most common letter) <= k
static int longestRun(String s, int k) {
int[] counts = new int[26];
int maxCount = 0;
int best = 0;
int left = 0;
for (int right = 0; right < s.length(); right++) {
maxCount = Math.max(maxCount, ++counts[s.charAt(right) - 'A']);
while (right - left + 1 - maxCount > k) {
counts[s.charAt(left) - 'A']--; // too many changes needed: shrink
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}
public static void main(String[] args) {
Object[][] cases = {{"ABBBCA", 1}, {"AAAA", 2}, {"ABCDE", 1}};
for (Object[] c : cases) {
System.out.println("\"" + c[0] + "\", k=" + c[1] + " -> " + longestRun((String) c[0], (Integer) c[1]));
}
}
}
"ABBBCA", k=1 -> 4 "AAAA", k=2 -> 4 "ABCDE", k=1 -> 2
Time complexity: O(n) · Space complexity: O(1).
Approach 2: One Target Letter at a Time
Each window is easy to reason about, at the cost of 26 passes over the string.
public class ReplacementPerLetter {
// For each target letter, find the longest window with at most k other letters
static int longestRun(String s, int k) {
int best = 0;
for (char target = 'A'; target <= 'Z'; target++) {
int others = 0;
int left = 0;
for (int right = 0; right < s.length(); right++) {
if (s.charAt(right) != target) {
others++;
}
while (others > k) {
if (s.charAt(left) != target) {
others--;
}
left++;
}
best = Math.max(best, right - left + 1);
}
}
return best;
}
public static void main(String[] args) {
Object[][] cases = {{"ABBBCA", 1}, {"AAAA", 2}, {"ABCDE", 1}};
for (Object[] c : cases) {
System.out.println("\"" + c[0] + "\", k=" + c[1] + " -> " + longestRun((String) c[0], (Integer) c[1]));
}
}
}
"ABBBCA", k=1 -> 4 "AAAA", k=2 -> 4 "ABCDE", k=1 -> 2
Time complexity: O(26 × n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Sliding Window With Max Count | O(n) | O(1) |
| One Target Letter at a Time | O(26 × n) | O(1) |
Here n is the length of the string. The single window moves each pointer at most n times; the per-letter version repeats that for 26 letters, which is still linear.
Interview Tips and Recommended Approach
- State the window rule clearly:
windowLength - maxCount <= k. - Be ready to defend the stale
maxCount. It is the subtle point interviewers ask about. - Offer the per-letter version first if unsure. It is easier to prove and still
O(n)for a fixed alphabet. - Know the family: variable windows with a validity rule also solve the longest substring without repeats and the minimum window problems.
Recommended Approach: Sliding Window With Max Count
Why: it solves the problem in one linear pass with a 26-element array, and the window rule generalises to many other substring questions.