Binary String With Substrings Representing 1 To N - Problem

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.

Input & Output

Example 1 — All Found
$ Input: s = "0110", n = 3
Output: true
💡 Note: Binary representations: 1="1", 2="10", 3="11". All are substrings of "0110": "1" at index 1, "10" at index 1, "11" at index 2.
Example 2 — Missing Number
$ Input: s = "0110", n = 4
Output: false
💡 Note: Binary of 4 is "100". The string "0110" does not contain "100" as a substring, so return false.
Example 3 — Single Digit
$ Input: s = "1", n = 1
Output: true
💡 Note: Only need to check if binary of 1 ("1") exists in "1", which it does.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s[i] is either '0' or '1'
  • 1 ≤ n ≤ 109

Visualization

Tap to expand
Binary String With Substrings [1 to N] INPUT Binary String s: 0 1 1 0 0 1 2 3 n = 3 Numbers to find: 1 = "1" 2 = "10" 3 = "11" Input Values s = "0110" n = 3 ALGORITHM STEPS 1 Start from N Check n=3 first (larger numbers harder to find) 2 Convert to Binary 3 --> "11" 2 --> "10", 1 --> "1" 3 Search in String Find each binary as substring in s 4 Verify All Found Return true if all substrings present Search Results in "0110": "11" at pos 1 [OK] "10" at pos 2 [OK] "1" at pos 1 [OK] FINAL RESULT All substrings found: 3 = "11" [OK] 2 = "10" [OK] 1 = "1" [OK] Output: true All integers from 1 to 3 are substrings of "0110" Key Insight: Reverse order search is efficient because larger numbers have longer binary representations, which are less likely to appear as substrings. If they don't exist, we can fail fast without checking all smaller numbers. Also, finding "11" often means "1" is also present. TutorialsPoint - Binary String With Substrings Representing 1 To N | Reverse Order Search
Asked in
Google 35 Facebook 28
32.0K Views
Medium Frequency
~15 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen