Skip to content

Commit c1b5a71

Browse files
committed
Time: 14 ms (31.71%) Space: 59 MB (19.51%)
1 parent 61eefea commit c1b5a71

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
};

0 commit comments

Comments
 (0)