#1016

Binary String With Substrings Representing 1 To N

Medium
Hash TableStringBit ManipulationSliding WindowHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n * m), where m is the average length of binary representations (up to 30).
O(n + m), where m is the number of unique binary representations.
Space
O(1)
O(n)
💡

Intuition

Time O(n + m), where m is the number of unique binary representations.Space O(n)

The optimal approach leverages the fact that we only need to check binary representations up to 30 bits. We can use a set to store these representations and check them against the string s efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a set to store binary representations of numbers from 1 to n.
  2. 2Step 2: Loop through numbers from 1 to n and add their binary representations to the set.
  3. 3Step 3: For each binary representation, check if it exists in the string s.
  4. 4Step 4: If all representations are found, return true; otherwise, return false.
solution.py5 lines
1# Full working Python code
2
3def queryString(s, n):
4    binaries = {bin(i)[2:] for i in range(1, n + 1)}
5    return all(b in s for b in binaries)

Complexity note: The time complexity is O(n + m) because we generate binary strings for numbers up to n and check them against s. The space complexity is O(n) due to storing binary representations.

  • 1We only need to check binary representations up to 30 bits due to the limit of n.
  • 2Using a set for storing binary representations allows for efficient membership checking.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.