Longest Repeating Character Replacement
LeetCode 424 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
valid ⇔ window − maxFreq ≤ k.
ನಾನು Longest Repeating Character Replacement (LeetCode 424) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Variable Window – Longest ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
In a window, the cheapest way to make all characters equal is to keep the most frequent one and replace the rest. A window is valid while (length − max frequency) ≤ k; otherwise shrink it by one from the left.
Approach
- 1
Add s[r] to the counts.
- 2
changes = window size − highest count.
- 3
If changes > k, remove s[l] and move l.
- 4
Track the best valid window length.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Sliding windowPythonO(n·26) time
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
#BAB, {B:2,A:1}, change 1
#ABAB {A:2,B:2}
#AABABBA
#BABB
#{A:1,B:3}
#substring - sliding window and two pointer
#maintain frequency of the elements of the current window
#changes = current num of elements in the current window - count of top frequency element
#if changes are more shrink from left
l=0
r=0
mpp = defaultdict(int)
max_length=0
while r<len(s):
cur = s[r]
mpp[cur]+=1
#find the maximum freq of the elements in the current window
max_freq = max(mpp.values())
no_of_changes = r-l+1 - max_freq
if no_of_changes>k:
mpp[s[l]]-=1
l+=1
if no_of_changes<=k:
max_length=max(max_length,r-l+1)
r+=1
return max_length
Longest Repeating Character Replacement — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Longest Repeating Character Replacement ಹಿಂದಿನ intuition ಏನು?
In a window, the cheapest way to make all characters equal is to keep the most frequent one and replace the rest. A window is valid while (length − max frequency) ≤ k; otherwise shrink it by one from the left.
Longest Repeating Character Replacement (LeetCode 424) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Add s[r] to the counts. 2. changes = window size − highest count. 3. If changes > k, remove s[l] and move l. 4. Track the best valid window length.
Longest Repeating Character Replacement ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(26 · n). Space: O(26). (Accepted approach: Sliding window.)
Longest Repeating Character Replacement ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
max(mpp.values()) each step is O(26) — fine; tracking a running max avoids it.