340. Longest Substring with At Most K Distinct Characters
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the length of the longest substring of a given string s that contains at most k distinct characters. This is a classic example of a problem that can be efficiently solved using the sliding window technique.
Solution
Longest Substring with At Most K Distinct Characters in Python
class Solution:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
# Handle the edge case where k is 0. No characters are allowed.
if k == 0:
return 0
max_length = 0
left = 0
# Dictionary to store frequency of characters in the current window.
freq = {}
# Use 'right' to expand the window.
for right, char in enumerate(s):
# Add the current character to the window.
freq[char] = freq.get(char, 0) + 1
# If the number of distinct characters exceeds k, shrink the window from the left.
while len(freq) > k:
left_char = s[left]
freq[left_char] -= 1
# If the frequency becomes 0, remove the character from the dictionary.
if freq[left_char] == 0:
del freq[left_char]
# Move the left pointer to shrink the window.
left += 1
# Update the maximum length found so far.
# The current window is from index 'left' to 'right', so its length is right - left + 1.
max_length = max(max_length, right - left + 1)
return max_length
Longest Substring with At Most K Distinct Characters in Java
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
// Handle the edge case where k is 0. No characters are allowed.
if (k == 0) {
return 0;
}
int maxLength = 0;
int left = 0;
// Map to store frequency of characters in the current window.
Map<Character, Integer> freq = new HashMap<>();
// Use 'right' to expand the window.
for (int right = 0; right < s.length(); right++) {
char rightChar = s.charAt(right);
// Add the current character to the window.
freq.put(rightChar, freq.getOrDefault(rightChar, 0) + 1);
// If the number of distinct characters exceeds k, shrink the window from the left.
while (freq.size() > k) {
char leftChar = s.charAt(left);
freq.put(leftChar, freq.get(leftChar) - 1);
// If the frequency becomes 0, remove the character from the map.
if (freq.get(leftChar) == 0) {
freq.remove(leftChar);
}
// Move the left pointer to shrink the window.
left++;
}
// Update the maximum length found so far.
// The current window is [left, right], so its length is right - left + 1.
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
}
Longest Substring with At Most K Distinct Characters in C++
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
// Handle the edge case where k is 0. No characters are allowed.
if (k == 0) {
return 0;
}
int maxLength = 0;
int left = 0;
// Map to store frequency of characters in the current window.
unordered_map<char, int> freq;
// Use 'right' to expand the window.
for (int right = 0; right < s.length(); ++right) {
// Add the current character to the window.
freq[s[right]]++;
// If the number of distinct characters exceeds k, shrink the window from the left.
while (freq.size() > k) {
char leftChar = s[left];
freq[leftChar]--;
// If the frequency becomes 0, remove the character from the map.
if (freq[leftChar] == 0) {
freq.erase(leftChar);
}
// Move the left pointer to shrink the window.
left++;
}
// Update the maximum length found so far.
// The current window is [left, right], so its length is right - left + 1.
maxLength = max(maxLength, right - left + 1);
}
return maxLength;
}
};
Longest Substring with At Most K Distinct Characters in TypeScript
function lengthOfLongestSubstringKDistinct(s: string, k: number): number {
// Handle the edge case where k is 0. No characters are allowed.
if (k === 0) {
return 0;
}
let maxLength = 0;
let left = 0;
// Map to store frequency of characters in the current window.
const freq = new Map<string, number>();
// Use 'right' to expand the window.
for (let right = 0; right < s.length; right++) {
const rightChar = s[right];
// Add the current character to the window.
freq.set(rightChar, (freq.get(rightChar) || 0) + 1);
// If the number of distinct characters exceeds k, shrink the window from the left.
while (freq.size > k) {
const leftChar = s[left];
freq.set(leftChar, freq.get(leftChar)! - 1);
// If the frequency becomes 0, remove the character from the map.
if (freq.get(leftChar) === 0) {
freq.delete(leftChar);
}
// Move the left pointer to shrink the window.
left++;
}
// Update the maximum length found so far.
// The current window is [left, right], so its length is right - left + 1.
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.