Binary String With Substrings Representing 1 To N Problem
Description
LeetCode Problem 1016.
Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "0110", n = 3
Output: true
Example 2:
Input: s = "0110", n = 4
Output: false
Constraints:
1 <= s.length <= 1000s[i]is either'0'or'1'.1 <= n <= 10^9
Solution
Approach: Bound n, then Check the Upper Half
n can be up to 109, so checking every number from 1 to n looks hopeless. Two observations make the work small.
Large n is impossible. Different numbers with the same number of bits need different starting positions in s. If n > 2047, s would have to contain all 1024 numbers from 1024 to 2047, which have 11 bits each, but a string of at most 1000 characters has fewer than 1000 places where an 11-character substring can start. So for n > 2047 the answer is false right away.
Only the upper half matters. If the binary form of x appears in s, so does the binary form of x / 2: it is the same substring without its last bit. Now take any y <= n / 2. Doubling it again and again, we land on some y * 2^t in the range n / 2 + 1 .. n, and its binary form starts with y's binary form. So if every number in that range is in s, every smaller number is too.
So for n <= 2047 we only check the numbers from n / 2 + 1 to n, with a plain substring search for each binary form.
Complexity: O(n · m · log n) time in the worst case, where m = len(s) and n ≤ 2047 at that point, and O(log n) extra space for each binary string.
class Solution:
def queryString(self, s: str, n: int) -> bool:
# n > 2047 needs all of 1024..2047 (11 bits each), but s has fewer than 1000 places to start one.
if n > 2047:
return False
# If x is in s, so is x // 2 (drop the last bit), so checking the upper half is enough.
return all(bin(x)[2:] in s for x in range(n, n // 2, -1))