Longest Substring with K Unique Characters
Find the length of the longest run of characters in a string that uses exactly k different characters.
Given a string sksksk
Example 1
Output: 7
Explanation: "cbebebe" has exactly 3 distinct characters: c, b and e.
Example 2
Output: -1
Explanation: the string has only one distinct character.
The Idea
Look at a word such as "banana". It is six letters long, but it uses only three different letters: b, a and n. This problem is about that second number, the different characters, which we will call kinds. We want the longest run of characters that uses exactly k
In Example 1, s = "aabacbebebe"k = 3
Lay a frame, or window, over the string. Its right edge moves one character at a time. Whenever the window holds more than kk
The first row shows the window over positions 0 to 5: "aabacb", 3 kinds, length 6. In the second row, e comes in at position 6, and the window has 4 kinds, too many. In the third row, a, a, b, a leave from the left. Dropping only the first three would not be enough, because another a still sits at position 3. Once it goes, the window "cbe" has 3 kinds again.
In the last row, the right edge has reached position 10. The window "cbebebe" still has 3 kinds, c, b and e, and its length, 7, is the answer. Each edge only moves forward, so the whole string is read in one sweep. A window whose two edges move forward like this is called a sliding window.
One more thing matters: a window counts toward the answer only when it holds exactly k
Solution Approach
Turning that idea into code means settling four things: how to count the kinds in the window, when to move the left edge, which windows to record, and what to return when no window has k
Counting the kinds in the window
Why not simply check every substring? A string of n characters has n(n + 1)/2 substrings: 66 for Example 1, but about 50 million for 10,000 characters. The window needs one sweep instead, as long as it always knows how many kinds it holds.
How does it keep that number up to date? An array countdistinctdistinctdistinct
The array has 128 entries, one for each ASCII character. ASCII is the basic set of 128 letters, digits and symbols, and a Java char
Moving the left edge
When does the left edge, leftdistinctkleftleft
Because the left edge moves only when it must, the window after these steps is the longest run ending at the right edge with at most k
Recording only windows with exactly k kinds
Which windows count? Only those where distinctkkk
Containing the substring, the window has at least kkk
When no window has k kinds
What if the window never reaches kk = 2best
Java Solution
The method longestKSubstr
- First, create
, an array of 128 zeros, and setcount to 0, the left edgedistinct to 0 andleft to -1.best - A loop moves the right edge,
, overright one position at a time. It adds one to the count ofs , and if that count was 0, it adds one tos.charAt(right) .distinct - Inside it, a
loop runs as long aswhile is greater thandistinct . It takes one off the count ofk , lowerss.charAt(left) if that count reaches 0, and movesdistinct one place right.left - If
now equalsdistinct , the window's length isk , andright - left + 1 keeps the larger of the two.best - After the right edge has passed the last character, return
, which is still -1 if no window had exactlybest kinds.k
The maink = 2k = 1
public class LongestSubstringWithKUniqueCharacters {
// Longest substring with exactly k distinct characters, or -1 if there is none
public static int longestKSubstr(String s, int k) {
int[] count = new int[128];
int distinct = 0;
int left = 0;
int best = -1;
for (int right = 0; right < s.length(); right++) {
if (count[s.charAt(right)]++ == 0) {
distinct++; // a new kind of character came in
}
while (distinct > k) {
if (--count[s.charAt(left)] == 0) {
distinct--; // the last copy of a character left
}
left++;
}
if (distinct == k) {
best = Math.max(best, right - left + 1); // only exact matches count
}
}
return best;
}
public static void main(String[] args) {
System.out.println(longestKSubstr("aabacbebebe", 3));
System.out.println(longestKSubstr("aaaa", 2));
System.out.println(longestKSubstr("aabbcc", 2));
System.out.println(longestKSubstr("ab", 1));
System.out.println(longestKSubstr("", 1));
}
}
Running it prints:
7
-1
4
1
-1
The 7 and the -1 at the top match the two examples. The 4 below them comes from "aabbcc" with k = 2
The 1 on the fourth line is "ab" with k = 1best
Why does the check distinct == kk = 2
The original implementation,
Complexity
The work is one sweep of the right edge, plus the steps of the left edge, which never moves back.
- Time: O(n), because the right edge visits each of the n characters of
once, and the left edge only moves forward, so it takes at most n steps over the whole run, not n steps per character.s - Space: O(1). The
array always has 128 entries, one per ASCII character, however longcount is, and the rest are fours variables.int
The same window without the exact check, recording every window with up to k