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 s and an integer k, return the length of the longest substring of s that contains at most k different characters. A substring is a run of characters that sit next to each other in s, such as "ece" in "eceba".

Example 1
Input: s = "eceba", k = 2
Output: 3
Explanation: "ece" has 2 different characters, e and c.
Example 2
Input: s = "aa", k = 1
Output: 2
Example 3
Input: s = "aabbcc", k = 2
Output: 4
Explanation: "aabb" or "bbcc".
Solution

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, the frame may show at most two kinds. "ece" is allowed, and its length is 3. "eceb" holds three kinds, e, c and b, so it is not. A string of 5 characters has 15 substrings, and one of 10,000 characters has about 50 million. Checking each one and counting its kinds is slow. So which substrings are worth looking at?

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.

The frame over eceba with k = 2, in four rows. Row 1: ece holds e and c, 2 kinds, length 3. Row 2: adding b makes eceb, 3 kinds, too many. Row 3: removing the first e leaves ceb, still 3 kinds. Row 4: removing c leaves eb, 2 kinds.

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, left and right.

right steps over the string once and takes one character into the window at each step. Whenever the window holds more than k kinds, left moves right, removing characters, until the window holds k kinds or fewer again. Moving left forward loses nothing. left leaves a position only when the window starting there already holds too many kinds. Any substring that starts at that position and ends at right or later contains that window, so it has too many kinds as well.

Counting the kinds in the window

How do we know the number of kinds without looking at the whole window again? Keep an array count with one slot per character, holding how many copies of that character are in the window. Next to it, keep distinct, the number of kinds.

When a character comes in and its count goes from 0 to 1, it is a new kind, and distinct goes up. When a character leaves and its count drops from 1 to 0, its last copy is gone, and distinct goes down. That is row 3 of the picture: the first e leaves, the count of e drops from 2 to 1, and distinct stays at 3.

In Java a char is a number, so it can index an array directly. 128 slots cover every ASCII character: the letters, digits and symbols of plain English text. If the text may hold other characters, such as accented letters, a HashMap<Character, Integer> can take the place of the array.

Recording the longest window

When is a length worth recording? Once left has stopped moving, the window from left to right holds at most k kinds, and it is the longest such window that ends at right. Its length, right - left + 1, is a candidate, and best keeps the largest one. For "eceba", best reaches 3 at row 1 of the picture and stays there.

Java Solution

The method lengthOfLongestSubstringKDistinct works in these steps:

  1. First, create the array count with 128 slots, all 0, and three numbers: distinct, the number of kinds in the window, left, where the window starts, and best, the longest length so far.
  2. A loop moves right over every position of s. It takes s.charAt(right) into the window by adding 1 to its count. If that count was 0 before, the character is a new kind, so distinct goes up.
  3. Inside that loop, a while loop runs as long as distinct is larger than k. It takes 1 off the count of s.charAt(left) and moves left one step right. When that count reaches 0, the last copy has left, so distinct goes down.
  4. After the while loop, the window holds at most k kinds. Its length, right - left + 1, replaces best if it is larger.
  5. When right has visited every character, return best.

The main method runs the three examples, "aabbcc" with k = 1, a k larger than the number of kinds in the string, k = 0, and an empty string.

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

Output
"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 -> 4. When right reaches the first c, the window holds a, b and c, and left has to pass both a's before a is gone. The window "bbc" then grows to "bbcc", length 4, the same as "aabb" reached earlier. With k = 1, the same string gives 2, from a single pair such as "aa".

"abcabc" has only three kinds, so with k = 5 the while loop never runs and the whole string, 6 characters, counts. With k = 0, every new character makes distinct larger than k, so the window is emptied at once and its length is 0 at every step. The empty string never enters the loop, and best stays 0.

The check --count[s.charAt(left)] == 0 matters. A version that lowers distinct on every removal returns 5 for "aabbcc" with k = 2. It drops distinct to 2 as soon as the first a leaves, while the second a is still inside. It then accepts "abbcc", which has three kinds.

Complexity

The work is one pass of right plus the steps of left, and both only move forward.

  • Time: O(n), because right visits each of the n characters once, and left passes each character at most once over the whole run. So the while loop runs at most n times in total, not n times for every right.
  • Space: O(1), because the count array has 128 slots however long s is, and the rest is four numbers.

With k = 2, the same window solves Fruits Into Basket.