Check If a String Contains All Binary Codes of Size K in C++


Suppose we have a binary string s and an integer k. We have to check whether every binary code of length k is a substring of s. Otherwise, return False.

So, if the input is like S = "00110110", k = 2, then the output will be true. The binary codes of length 2 are "00", "01", "10" and "11". These are present at indices 0, 1, 3, and 2 respectively.

To solve this, we will follow these steps −

  • Define one set v

  • temp := blank string

  • req := 2^k

  • for initialize i := 0, when i < size of s, update (increase i by 1), do −

    • temp := temp + s[i]

    • if i >= k, then −

      • delete one character from the first index of temp

    • if i >= k - 1, then −

      • insert temp into v

    • if size of v is same as req, then −

      • return true

  • return false

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
   lli fastPow(lli b, lli p){
      lli ret = 1;
      while (p) {
         if (p & 1) {
            ret *= b;
         }
         b *= b;
         p >>= 1;
      }
      return ret;
   }
   bool hasAllCodes(string s, int k) {
      unordered_set<string> v;
      string temp = "";
      lli req = fastPow(2, k);
      for (lli i = 0; i < s.size(); i++) {
         temp += s[i];
         if (i >= k) {
            temp.erase(0, 1);
         }
         if (i >= k - 1) {
            v.insert(temp);
         }
         if ((lli)v.size() == req)
            return true;
      }
      return false;
   }
};
main(){
   Solution ob;
   cout << (ob.hasAllCodes("00110110",2));
}

Input

"00110110",2

Output

1

Updated on: 18-Nov-2020

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements