File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
longest-repeating-character-replacement Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change 1+ // TC: O(n)
2+ // SC: O(1)
3+ function characterReplacement ( s : string , k : number ) : number {
4+ const freqMap = new Map < string , number > ( ) ;
5+ let left = 0 ;
6+ let maxFreqCnt = 0 ;
7+ let result = 0 ;
8+
9+ for ( let right = 0 ; right < s . length ; right ++ ) {
10+ const ch = s [ right ] ;
11+ freqMap . set ( ch , ( freqMap . get ( ch ) ! | 0 ) + 1 ) ;
12+ maxFreqCnt = Math . max ( maxFreqCnt , freqMap . get ( ch ) ! ) ;
13+
14+ while ( right - left + 1 - maxFreqCnt > k ) {
15+ // Shrink the sliding window by moving the left pointer to the right.
16+ // As we move left, decrease the frequency count of the character being excluded from the window.
17+ const ch = s [ left ] ;
18+ freqMap . set ( ch , freqMap . get ( ch ) ! - 1 ) ;
19+ left ++ ;
20+ }
21+
22+ result = Math . max ( result , right - left + 1 ) ;
23+ }
24+
25+ return result ;
26+ }
27+
You can’t perform that action at this time.
0 commit comments