#424
Longest Repeating Character Replacement
MediumHash TableStringSliding WindowSliding WindowTwo PointersHash Map
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a sliding window approach to efficiently find the longest substring that can be transformed into a repeating character substring with at most k replacements. This reduces the need to check every substring individually.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers (left and right) to represent the current window and a variable to count the maximum frequency of any character in the current window.
- 2Step 2: Expand the right pointer to include more characters in the window.
- 3Step 3: Update the frequency of the current character and the maximum frequency found in the window.
- 4Step 4: If the current window size minus the maximum frequency is greater than k, move the left pointer to shrink the window until the condition is satisfied.
- 5Step 5: Update the maximum length of the valid window found during the process.
solution.py16 lines
1# Full working Python code
2
3def characterReplacement(s, k):
4 left = 0
5 count = [0] * 26
6 max_count = 0
7 max_length = 0
8 for right in range(len(s)):
9 count[ord(s[right]) - ord('A')] += 1
10 max_count = max(max_count, count[ord(s[right]) - ord('A')])
11 while (right - left + 1) - max_count > k:
12 count[ord(s[left]) - ord('A')] -= 1
13 left += 1
14 max_length = max(max_length, right - left + 1)
15 return max_length
16ℹ
Complexity note: The time complexity is O(n) because we traverse the string with two pointers, and each character is processed at most twice. The space complexity is O(1) since we use a fixed-size array for character counts.
- 1Using a sliding window allows us to efficiently track the longest valid substring without generating all substrings.
- 2The maximum frequency of characters helps determine how many replacements are needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.