Longest Substring with K Distinct Characters

for (let windowEnd = 0; windowEnd < str.length; windowEnd++) {const rightChar = str[windowEnd];if (!(rightChar in charFrequency)) {charFrequency[rightChar] = 0;}charFrequency[rightChar] += 1;while (Object.keys(charFrequency).length > k) {const leftChar = str[windowStart];charFrequency[leftChar] -= 1;if (charFrequency[leftChar] === 0) {delete charFrequency[leftChar];}windowStart += 1; // shrink the window}maxLength = Math.max(maxLength, windowEnd - windowStart + 1);}return maxLength;}

Time Complexity

Space Complexity

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store