Back to Dashboard
Longest Substring with K Distinct Characters
MediumProblem Statement
Given a string, find the length of the longest substring in it with no more than K distinct characters.
You can assume that K is less than or equal to the length of the given string.
Examples
Example 1:
- Input:
String="araaci", K=2 - Output:
4
Approach 1 Sliding Window:
public int findLength(String str, int k) {
var maxLength = 0;
var len = 0;
var windowStart = 0;
var charCountMap = new HashMap<Character, Integer>();
for (var windowEnd = 0; windowEnd < str.length(); windowEnd ++) {
len ++;
var endCh = str.charAt(windowEnd);
charCountMap.put(endCh, charCountMap.getOrDefault(endCh, 0) + 1);
while (charCountMap.size() > k) {
var startCh = str.charAt(windowStart);
if (charCountMap.containsKey(startCh)) {
charCountMap.put(startCh, charCountMap.get(startCh) - 1);
if (charCountMap.get(startCh) == 0) {
charCountMap.remove(startCh);
}
}
windowStart ++;
len --;
}
maxLength = Math.max(maxLength, len);
}
return maxLength;
}