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 sktrueksfalse
Example 1
Output: true
Explanation: 00, 01, 10 and 11 all appear.
Example 2
Output: true
Example 3
Output: false
Explanation: 00 does not appear.
The Idea
Think of a row of kkkk
The question is whether all 2k codes show up inside ssks = "00110110"k = 2
In Example 3, s = "0110"
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 kseen
Window 1 is 00, code 0, so box 0 of seentrue
Solution Approach
Turning that idea into code means settling four things: when the answer is false
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"01"k = 3
Remembering which codes appeared
The simple way is to cut each window out with substringHashSetk
With each window read as a number instead, a booleanseenseen[code]found
Moving the window by one character
How do we get the next window's number without reading all k
shifts every bit one place left, which doubles the number: 3, binary 11, becomes 6, binary 110.code << 1 puts the new character, as a bit, into the empty rightmost place. The OR operator| bit sets a bit wherever either number has a 1. The new character here is 0, so 110 stays 6.| keeps only the last& mask bits, which drops the character that left the window. The AND operatork keeps a bit only where both numbers have a 1.& is 2k - 1, binary 11 formask , and 110 & 011 is 010, which is 2.k = 2
The result, 2, is the code of window 4. Each move costs the same three steps, however large k
The first window
The rolling number starts at 0 and takes in one character per step, so it holds a full window only after kkk - 1
Java Solution
The method hasAllCodes
- First, work out the number of codes,
, which is 2k. Iftotal = 1 << k has fewer thans windows, returntotal straight away.false - Create the
arrayboolean with one box per code, theseenmask , the rolling numbertotal - 1 starting at 0, and the countercode starting at 0.found - A loop moves
over every character ofi . At each one, shifts left, add the new bit, and applycode .mask - Once
reachesi ,k - 1 is a full window. Ifcode is stillseen[code] , mark it and add one tofalse . Whenfound reachesfound , returntotal without reading the rest.true - If the loop ends first, some code never appeared, so return
.false
The main
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:
true
true
false
false
false
true
The first three lines, truetruefalsefalse"01"k = 3
Look at the fifth line. The windows of "11100"falsei >= k - 1codetrue
The last line is true"0001011100"
The original implementation,
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
has one box for each possible code, which is about a million boxes whenseen .k = 20
Keeping a window as a rolling number also lets