Longest Substring with at most K Distinct Characters
Find the length of the longest substring that uses at most k different characters.
Given a string sksks
Example 1
Output: 3
Explanation: "ece" has 2 different characters, e and c.
Example 2
Output: 2
Example 3
Output: 4
Explanation: "aabb" or "bbcc".
The Idea
Picture the word "eceba" on a strip of paper, with a frame you can slide over it and stretch or shrink. Whatever the frame shows is a substring. Call each different character in it a kind: "ece" holds two kinds, e and c.
With k = 2
Think about what stretching does. "eceb" already has three kinds, so "eceba", which starts at the same place and goes further, has at least three as well. Making the frame longer never lowers its number of kinds. So once the frame holds one kind too many, its left end has to move right, and it never needs to come back. Look at the picture below.
In the row labelled "1. add the second e", the frame covers "ece": 2 kinds, length 3. In row 2, the right end takes in b, and the frame holds three kinds, one too many. Row 3 removes the first e from the left, yet the frame still holds 3 kinds, because the second e is still inside. Only in row 4, after c leaves, is it back to two kinds, e and b.
So both ends of the frame move forward only. The right end takes in one character at a time, and the left end follows only when it has to. A frame like this is called a sliding window. Row 3 also shows what to keep track of: not how many characters left the window, but how many copies of each kind are still inside it.
Solution Approach
Turning the picture into code means settling three things: how the two ends of the window move, how to count the kinds inside it, and when to record the answer.
Moving the two ends of the window
Why not try every substring? Two loops, one for the start and one for the end, give about n²/2 substrings for a string of n characters, and each one needs its kinds counted. The window needs only two positions, leftright
rightkleftkleftleftright
Counting the kinds in the window
How do we know the number of kinds without looking at the whole window again? Keep an array countdistinct
When a character comes in and its count goes from 0 to 1, it is a new kind, and distinctdistinctdistinct
In Java a charHashMap<Character, Integer>
Recording the longest window
When is a length worth recording? Once leftleftrightkrightright - left + 1bestbest
Java Solution
The method lengthOfLongestSubstringKDistinct
- First, create the array
with 128 slots, all 0, and three numbers:count , the number of kinds in the window,distinct , where the window starts, andleft , the longest length so far.best - A loop moves
over every position ofright . It takess into the window by adding 1 to its count. If that count was 0 before, the character is a new kind, sos.charAt(right) goes up.distinct - Inside that loop, a
loop runs as long aswhile is larger thandistinct . It takes 1 off the count ofk and movess.charAt(left) one step right. When that count reaches 0, the last copy has left, soleft goes down.distinct - After the
loop, the window holds at mostwhile kinds. Its length,k , replacesright - left + 1 if it is larger.best - When
has visited every character, returnright .best
The maink = 1kk = 0
public class LongestSubstringWithKDistinctCharacters {
public static int lengthOfLongestSubstringKDistinct(String s, int k) {
int[] count = new int[128]; // count of each character in the window
int distinct = 0;
int left = 0;
int best = 0;
for (int right = 0; right < s.length(); right++) {
if (count[s.charAt(right)]++ == 0) {
distinct++; // a character new to the window
}
while (distinct > k) {
if (--count[s.charAt(left)] == 0) {
distinct--; // its last copy left the window
}
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}
static void show(String s, int k) {
System.out.println("\"" + s + "\", k = " + k + " -> "
+ lengthOfLongestSubstringKDistinct(s, k));
}
public static void main(String[] args) {
show("eceba", 2);
show("aa", 1);
show("aabbcc", 2);
show("aabbcc", 1);
show("abcabc", 5);
show("abc", 0);
show("", 2);
}
}
Running it prints:
"eceba", k = 2 -> 3
"aa", k = 1 -> 2
"aabbcc", k = 2 -> 4
"aabbcc", k = 1 -> 2
"abcabc", k = 5 -> 6
"abc", k = 0 -> 0
"", k = 2 -> 0
Look at the line "aabbcc", k = 2 -> 4rightleftk = 1
"abcabc" has only three kinds, so with k = 5whilek = 0distinctkbest
The check --count[s.charAt(left)] == 0distinctk = 2distinct
Complexity
The work is one pass of rightleft
- Time: O(n), because
visits each of the n characters once, andright passes each character at most once over the whole run. So theleft loop runs at most n times in total, not n times for everywhile .right - Space: O(1), because the
array has 128 slots however longcount is, and the rest is four numbers.s
With k = 2