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 s and an integer k, return the length of the longest substring of s that contains exactly k distinct characters. A substring is a run of characters that sit next to each other in s. If no substring has exactly k distinct characters, return -1.

Example 1
Input: s = "aabacbebebe", k = 3
Output: 7
Explanation: "cbebebe" has exactly 3 distinct characters: c, b and e.
Example 2
Input: s = "aaaa", k = 2
Output: -1
Explanation: the string has only one distinct character.
Solution

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 kinds.

In Example 1, s = "aabacbebebe" and k = 3. The run "aabacb", at positions 0 to 5, uses a, b and c, so it has 3 kinds and is 6 long. It cannot grow to the right, because the e at position 6 would make 4 kinds. Yet further along, "cbebebe" uses only c, b and e and is 7 long. So the best run need not start at position 0. How do we find it without checking every run one by one?

Lay a frame, or window, over the string. Its right edge moves one character at a time. Whenever the window holds more than k kinds, its left edge moves right, dropping characters, until there are k kinds again. Look at the picture below.

A window slides over aabacbebebe with k = 3. The window aabacb has 3 kinds, length 6. Then e comes in and makes 4 kinds, too many. a, a, b, a leave, so the window cbe has 3 kinds. The window grows to cbebebe, 3 kinds, length 7, the answer.

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 kinds. Before the c arrives at position 4, the window "aaba" has only 2 kinds, so its length 4 is not an answer.

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 kinds.

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 count holds, for every character, how many copies of it are in the window. A variable distinct holds the number of kinds. When a character comes in and its count goes from 0 to 1, it is a new kind, so distinct goes up. When a character leaves and its count drops to 0, its last copy is gone, so distinct goes down.

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 in that range can be used directly as an index.

Moving the left edge

When does the left edge, left, move? Only while distinct is greater than k. Each step lowers the count of the character at left and moves left one place right. As the third row of the picture showed, this can take several steps before a kind is really gone.

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 kinds.

Recording only windows with exactly k kinds

Which windows count? Only those where distinct equals k. Could this miss the answer? Take the longest substring with exactly k kinds, and look at the window when the right edge reaches its last character. That window is the longest run ending there with at most k kinds, so it contains the substring.

Containing the substring, the window has at least k kinds, and it has at most k, so it has exactly k. It gets recorded, and its length is at least the substring's length.

When no window has k kinds

What if the window never reaches k kinds? In Example 2, "aaaa" has a single kind, so with k = 2 nothing qualifies. The longest length so far is kept in best, which starts at -1 and changes only when a window is recorded, so it stays -1.

Java Solution

The method longestKSubstr works in these steps:

  1. First, create count, an array of 128 zeros, and set distinct to 0, the left edge left to 0 and best to -1.
  2. A loop moves the right edge, right, over s one position at a time. It adds one to the count of s.charAt(right), and if that count was 0, it adds one to distinct.
  3. Inside it, a while loop runs as long as distinct is greater than k. It takes one off the count of s.charAt(left), lowers distinct if that count reaches 0, and moves left one place right.
  4. If distinct now equals k, the window's length is right - left + 1, and best keeps the larger of the two.
  5. After the right edge has passed the last character, return best, which is still -1 if no window had exactly k kinds.

The main method runs both examples, then "aabbcc" with k = 2, "ab" with k = 1, and an empty string.

Java
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:

Output
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: "aabb" and "bbcc" both have two kinds and length 4. When the first c comes in, the left edge drops both a's to get from 3 kinds back to 2.

The 1 on the fourth line is "ab" with k = 1: the window "a" is recorded first, and when b comes in, a leaves and "b" is recorded with the same length. The empty string gives the last -1, because the loop never runs and best keeps its starting value.

Why does the check distinct == k matter? A version without it records every window, including those with fewer kinds. We ran that version: on Example 1 it still returns 7, but on "aaaa" with k = 2 it returns 4 instead of -1, because the window "aaaa", with one kind, counts too.

The original implementation, LongestSubstringWithKUniqueChars.java, is on GitHub.

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 s once, and the left edge only moves forward, so it takes at most n steps over the whole run, not n steps per character.
  • Space: O(1). The count array always has 128 entries, one per ASCII character, however long s is, and the rest are four int variables.

The same window without the exact check, recording every window with up to k kinds, solves Longest Substring with at most K Distinct Characters.