Binary String With Substrings Representing 1 To N

You can solve this problem by iterating through the range of numbers from 1 to n, and for each number, you need to check whether its binary representation is a substring of the given string s.

Here’s the Python code:

1
2
3
4
5
6
7
8
9
class Solution:
    def queryString(self, s: str, n: int) -> bool:
        for i in range(1, n + 1):
            # Convert the integer to its binary representation
            binary_representation = bin(i)[2:]
            # Check whether the binary representation is a substring of s
            if binary_representation not in s:
                return False
        return True

Explanation:

  • We use a for loop to iterate through numbers from 1 to n.
  • For each number, we convert it to its binary representation using the bin function, and then we check whether this binary representation is a substring of s using the in keyword.
  • If we find any number whose binary representation is not a substring of s, we return False.
  • If all binary representations are substrings of s, we return True.