Leetcode 1016: Binary String With Substrings Representing 1 To N

grid47
grid47
Exploring patterns and algorithms
Jul 28, 2024 5 min read

Given a binary string s and a positive integer n, determine if the binary representation of all integers from 1 to n (inclusive) are substrings of s. A substring is defined as a contiguous sequence of characters within a string. Return true if all the binary representations of the integers in the range [1, n] are present as substrings of s, otherwise return false.
Problem
Approach
Steps
Complexity
Input: You are given a binary string s and a positive integer n.
Example: s = '110101', n = 4
Constraints:
• 1 <= s.length <= 1000
• s[i] is either '0' or '1'.
• 1 <= n <= 10^9
Output: Return true if the binary representation of all integers from 1 to n are substrings of s, otherwise return false.
Example: Output: true
Constraints:
• The output is a boolean value.
Goal: The goal is to check if the binary representation of all integers from 1 to n are substrings of s.
Steps:
• For each number i from 1 to n, convert the number to its binary representation.
• Check if the binary representation of i is a substring of s.
• If any number’s binary representation is not a substring of s, return false.
• If all numbers’ binary representations are substrings of s, return true.
Goal: You need to consider the constraints for string length and number size, especially given the potentially large value of n.
Steps:
• The length of s can be as large as 1000 characters.
• The value of n can be up to 10^9, so an efficient solution is needed.
Assumptions:
• The input string s is guaranteed to be valid and consist only of '0's and '1's.
Input: Input: s = '0110', n = 3
Explanation: The binary representations of 1, 2, and 3 are '1', '10', and '11', respectively. All these are substrings of '0110', so the output is true.

Input: Input: s = '0110', n = 4
Explanation: The binary representation of 4 is '100', which is not a substring of '0110', so the output is false.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus