Check if a String Contains all Binary Codes of Size K

Check whether every string of k zeros and ones appears somewhere inside a binary string.

Given a string s made only of the characters 0 and 1, and a number k, return true if every possible string of k zeros and ones appears in s as a run of consecutive characters. Otherwise return false.

Example 1
Input: s = "00110110", k = 2
Output: true
Explanation: 00, 01, 10 and 11 all appear.
Example 2
Input: s = "0110", k = 1
Output: true
Example 3
Input: s = "0110", k = 2
Output: false
Explanation: 00 does not appear.
Solution

The Idea

Think of a row of k light switches, each either off (0) or on (1). With two switches there are four settings: 00, 01, 10 and 11. Each extra switch doubles the count, so k switches give 2k settings. A string of k zeros and ones like these is called a binary code of length k.

The question is whether all 2k codes show up inside s. To find them, look at s through a frame that shows k characters at a time, and move the frame one character to the right after each look. That frame is called a window. In Example 1, s = "00110110" and k = 2, so the windows are 00, 01, 11, 10, 01, 11 and 10. All four codes are there.

In Example 3, s = "0110" gives only three windows: 01, 11 and 10. Four codes cannot fit into three windows, so one of them, 00, has to be missing. That leaves the real question: as the window moves along a long string, how do we keep track of which codes have appeared, without comparing strings again and again?

The answer is to read each window as a number. Written in base 2, where each place is worth twice the place to its right, 00 is 0, 01 is 1, 10 is 2 and 11 is 3. Every code of length k is a number from 0 to 2k - 1, so a row of 2k yes-or-no boxes, one per number, can record what has been seen. Look at the picture below, where those boxes are labelled seen.

The string 00110110 with its first four windows of length 2: 00 is code 0, 01 is code 1, 11 is code 3 and 10 is code 2. The seen boxes mark each code, and after window 4 all four codes 0 to 3 are seen, so the answer is true.

Window 1 is 00, code 0, so box 0 of seen gets marked. Window 2 is 01, code 1, and window 3 is 11, code 3. Window 4 is 10, code 2, and it fills the last empty box, the one highlighted in orange. All four boxes are marked after only four windows, so the answer is true and the rest of the string does not matter.

Solution Approach

Turning that idea into code means settling four things: when the answer is false before any scanning, how to remember the codes already seen (the simple way first), how to get each window's number from the one before it, and when the first window is complete.

Counting the windows

Can we sometimes answer without looking at the characters at all? A string of length n has n - k + 1 windows of length k. Each window shows one code, so with fewer than 2k windows some code must be missing. That is why Example 3 fails: 3 windows, 4 codes. A string like "01" with k = 3 has no window at all.

Remembering which codes appeared

The simple way is to cut each window out with substring and add it to a HashSet, then check whether the set has reached 2k strings. It works, but every window costs k characters to copy and hash, so the whole scan takes about n times k steps.

With each window read as a number instead, a boolean array seen of size 2k does the job of the set. seen[code] says whether that code has appeared, and a counter found goes up by one each time a box is marked for the first time.

Moving the window by one character

How do we get the next window's number without reading all k characters again? Take window 3 to window 4 in the picture, 11 to 10. Three bit operations do it, where a bit is one binary digit:

  • code << 1 shifts every bit one place left, which doubles the number: 3, binary 11, becomes 6, binary 110.
  • | bit puts the new character, as a bit, into the empty rightmost place. The OR operator | sets a bit wherever either number has a 1. The new character here is 0, so 110 stays 6.
  • & mask keeps only the last k bits, which drops the character that left the window. The AND operator & keeps a bit only where both numbers have a 1. mask is 2k - 1, binary 11 for k = 2, and 110 & 011 is 010, which is 2.

The result, 2, is the code of window 4. Each move costs the same three steps, however large k is. Keeping a window's value up to date this way, instead of recomputing it, is called a rolling value.

The first window

The rolling number starts at 0 and takes in one character per step, so it holds a full window only after k characters. Before that, it holds fewer than k real bits. That is why codes are recorded only from position k - 1 on.

Java Solution

The method hasAllCodes works in these steps:

  1. First, work out the number of codes, total = 1 << k, which is 2k. If s has fewer than total windows, return false straight away.
  2. Create the boolean array seen with one box per code, the mask total - 1, the rolling number code starting at 0, and the counter found starting at 0.
  3. A loop moves i over every character of s. At each one, shift code left, add the new bit, and apply mask.
  4. Once i reaches k - 1, code is a full window. If seen[code] is still false, mark it and add one to found. When found reaches total, return true without reading the rest.
  5. If the loop ends first, some code never appeared, so return false.

The main method runs the three examples, a string too short to hold one window, a string where the first-window check matters, and a string that holds all eight codes of length 3 in exactly eight windows.

Java
public class CheckIfAStringContainsAllBinaryCodesOfSizeK {

    public static boolean hasAllCodes(String s, int k) {
        int total = 1 << k;                   // there are 2^k codes of length k
        if (s.length() - k + 1 < total) {
            return false;                     // not enough windows to hold them all
        }
        boolean[] seen = new boolean[total];
        int mask = total - 1;                 // keeps only the last k bits
        int code = 0;
        int found = 0;
        for (int i = 0; i < s.length(); i++) {
            code = ((code << 1) | (s.charAt(i) - '0')) & mask;   // slide the window by one bit
            if (i >= k - 1 && !seen[code]) {
                seen[code] = true;
                if (++found == total) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(hasAllCodes("00110110", 2));
        System.out.println(hasAllCodes("0110", 1));
        System.out.println(hasAllCodes("0110", 2));
        System.out.println(hasAllCodes("01", 3));
        System.out.println(hasAllCodes("11100", 2));
        System.out.println(hasAllCodes("0001011100", 3));
    }
}

Running it prints:

Output
true
true
false
false
false
true

The first three lines, true, true and false, match the three examples. The fourth line is false from the window count alone: "01" is shorter than k = 3, so the loop never runs.

Look at the fifth line. The windows of "11100" are 11, 11, 10 and 00, so 01 is missing and the answer is false. Without the check i >= k - 1, the first step would record code = 1 after reading a single 1, and count it as 01. A copy of the method without that check, run on the same input, returns true.

The last line is true: "0001011100" has the windows 000, 001, 010, 101, 011, 111, 110 and 100, each of the eight codes once. Eight windows is the fewest that can hold eight codes, so the window count lets it through and the loop finishes the job.

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

Complexity

The work is one pass over the string, plus an array with a box for every possible code.

  • Time: O(n), because the loop reads each of the n characters once, and each step is a shift, an OR, an AND and one array lookup, whatever the value of k.
  • Space: O(2k), because seen has one box for each possible code, which is about a million boxes when k = 20.

Keeping a window as a rolling number also lets Repeated DNA Sequences avoid building substrings.