MediumNo. 0424
Longest Repeating Character Replacement — LeetCode 424 Python Solution
- Pattern
- Sliding Window
- Topics
- Hash Table, String, Sliding Window
- On study lists
- Blind 75 and NeetCode 150
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character.
Example
- Input
- s = "ABAB", k = 2
- Output
- 4
- Explanation
- Replace the two 'A's with two 'B's or vice versa.
Python solution
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
cnt = Counter()
l = mx = 0
for r, c in enumerate(s):
cnt[c] += 1
mx = max(mx, cnt[c])
if r - l + 1 - mx > k:
cnt[s[l]] -= 1
l += 1
return len(s) - lComplexity
- Time
- O(n)
- Space · auxiliary
- O(|Σ|)
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 424. Longest Repeating Character Replacement is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0003 | Longest Substring Without Repeating Characters | Medium |
| 0030 | Substring with Concatenation of All Words | Hard |
| 0076 | Minimum Window Substring | Hard |
| 0187 | Repeated DNA Sequences | Medium |
| 0395 | Longest Substring with At Least K Repeating Characters | Medium |
| 0438 | Find All Anagrams in a String | Medium |
Frequently asked questions
- How hard is LeetCode 424. Longest Repeating Character Replacement?
LeetCode 424. Longest Repeating Character Replacement is rated Medium on LeetCode.
- What is the time complexity of LeetCode 424. Longest Repeating Character Replacement?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 424. Longest Repeating Character Replacement?
The Python solution on this page uses O(|Σ|) auxiliary space.
- What topics does LeetCode 424. Longest Repeating Character Replacement cover?
LeetCode 424. Longest Repeating Character Replacement is tagged Hash Table, String and Sliding Window on LeetCode.