Skip to content

424. Longest Repeating Character Replacement 👍

Approach 1: Regular Window

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int characterReplacement(string s, int k) {
    int ans = 0;
    int maxCount = 0;
    vector<int> count(26);

    for (int l = 0, r = 0; r < s.length(); ++r) {
      maxCount = max(maxCount, ++count[s[r] - 'A']);
      while (maxCount + k < r - l + 1)
        --count[s[l++] - 'A'];
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int characterReplacement(String s, int k) {
    int ans = 0;
    int maxCount = 0;
    int[] count = new int[26];

    for (int l = 0, r = 0; r < s.length(); ++r) {
      maxCount = Math.max(maxCount, ++count[s.charAt(r) - 'A']);
      while (maxCount + k < r - l + 1)
        --count[s.charAt(l++) - 'A'];
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def characterReplacement(self, s: str, k: int) -> int:
    ans = 0
    maxCount = 0
    count = collections.Counter()

    l = 0
    for r, c in enumerate(s):
      count[c] += 1
      maxCount = max(maxCount, count[c])
      while maxCount + k < r - l + 1:
        count[s[l]] -= 1
        l += 1
      ans = max(ans, r - l + 1)

    return ans

Approach 2: Lazy Window

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int characterReplacement(string s, int k) {
    int maxCount = 0;
    vector<int> count(26);

    // l and r track the maximum window instead of the valid window.
    int l = 0;
    int r = 0;

    for (r = 0; r < s.length(); ++r) {
      maxCount = max(maxCount, ++count[s[r] - 'A']);
      if (maxCount + k < r - l + 1)
        --count[s[l++] - 'A'];
    }

    return r - l;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int characterReplacement(String s, int k) {
    int maxCount = 0;
    int[] count = new int[26];

    // l and r track the maximum window instead of the valid window.
    int l = 0;
    int r = 0;

    for (r = 0; r < s.length(); ++r) {
      maxCount = Math.max(maxCount, ++count[s.charAt(r) - 'A']);
      if (maxCount + k < r - l + 1)
        --count[s.charAt(l++) - 'A'];
    }

    return r - l;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def characterReplacement(self, s: str, k: int) -> int:
    maxCount = 0
    count = collections.Counter()

    # l and r track the maximum window instead of the valid window.
    l = 0
    for r, c in enumerate(s):
      count[c] += 1
      maxCount = max(maxCount, count[c])
      while maxCount + k < r - l + 1:
        count[s[l]] -= 1
        l += 1

    return r - l + 1