File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
0340-longest-substring-with-at-most-k-distinct-characters Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @time - O(n) where n is the length of s
3+ * (each character visited at most twice by sliding window pointers)
4+ * @space - O(k) where k is the maximum number of distinct characters allowed;
5+ * the map stores at most k + 1 characters at any time before shrinking
6+ */
7+ function lengthOfLongestSubstringKDistinct ( s : string , k : number ) : number {
8+ if ( k === 0 ) return 0 ;
9+
10+ const characterCount = new Map < string , number > ( ) ;
11+ let left = 0 ;
12+ let maxLength = 0 ;
13+
14+ // Expand the window by moving the right pointer
15+ for ( let right = 0 ; right < s . length ; right ++ ) {
16+ const char = s [ right ] ;
17+ // Add current character to frequency map
18+ characterCount . set ( char , ( characterCount . get ( char ) || 0 ) + 1 ) ;
19+
20+ // Shrink the window from the left if we have more than k distinct characters
21+ while ( characterCount . size > k ) {
22+ const leftChar = s [ left ] ;
23+ characterCount . set ( leftChar , characterCount . get ( leftChar ) ! - 1 ) ;
24+ // Remove the character from the map if its count drops to zero
25+ if ( characterCount . get ( leftChar ) === 0 ) {
26+ characterCount . delete ( leftChar ) ;
27+ }
28+ left ++ ;
29+ }
30+
31+ // Update the maximum length found so far
32+ maxLength = Math . max ( maxLength , right - left + 1 ) ;
33+ }
34+
35+ return maxLength ;
36+ } ;
You can’t perform that action at this time.
0 commit comments