Open In App

Check if binary representations of 0 to N are present as substrings in given binary string

Last Updated : 18 Jun, 2022
Comments
Improve
Suggest changes
2 Likes
Like
Report

Give binary string str and an integer N, the task is to check if the substrings of the string contain all binary representations of non-negative integers less than or equal to the given integer N.


Examples: 

Input: str = “0110", N = 3 
Output: True 
Explanation: 
Since substrings “0", “1", “10", and “11" can be formed from given string. Hence all binary representations of 0 to 3 are present as substrings in given binary string.

Input: str = “0110”, N = 4 
Output: False 
Explanation: 
Since substrings “0", “1", “10", and “11" can be formed from given string, but not "100". Hence the answer is False

 


Approach:  
The above problem can be solved using BitSet and HashMap. Follow the steps given below to solve the problem

  • Initialize a map[] to mark the strings and take a bit-set variable ans to convert the number from decimal to binary.
  • Take one more variable count as zero.
  • run the loop from N to 1 using the variable i and check the corresponding numbers are marked in a map or not.
  • if number i is not marked in a map[] then convert the current number into binary using the bit-set variable ans.
  • then check if converted binary string is substring of the given string or not.
  • if it is not a substring then
  • run while loop unless i is not marked and binary number becomes zero
    • mark the i in a map
    • increment the count
    • do the right shift of converted number. This is done because if any string x is converted into binary (say 111001) and this substring is already marked in map, then 11100 will already be marked automatically. 
      This is based on the fact that if i exists, i>>1 also exists.
  • Finally check if count ? N + 1, then print True 
    Else print False

Below is the implementation of above approach:

C++
Java Python3 C# JavaScript

Output: 
True

 


Time Complexity: O(N logN)
Auxiliary Space: O(N), as extra space of size N is used to make an array


Next Article

Similar Reads