1016. Binary String With Substrings Representing 1 To N LeetCode Solution
In this guide, you will get 1016. Binary String With Substrings Representing 1 To N LeetCode Solution with the best time and space complexity. The solution to Binary String With Substrings Representing To N problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Binary String With Substrings Representing To N solution in C++
- Binary String With Substrings Representing To N solution in Java
- Binary String With Substrings Representing To N solution in Python
- Additional Resources
Problem Statement of Binary String With Substrings Representing To N
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 <= 1000
s[i] is either '0' or '1'.
1 <= n <= 109
Complexity Analysis
- Time Complexity: O(|\texttt{s}|)
- Space Complexity: O(1)
1016. Binary String With Substrings Representing 1 To N LeetCode Solution in C++
class Solution {
public:
bool queryString(string s, int n) {
if (n > 1511)
return false;
for (int i = n; i > n / 2; --i) {
string binary = bitset<32>(i).to_string();
binary = binary.substr(binary.find("1"));
if (s.find(binary) == string::npos)
return false;
}
return true;
}
};
/* code provided by PROGIEZ */
1016. Binary String With Substrings Representing 1 To N LeetCode Solution in Java
class Solution {
public boolean queryString(String s, int n) {
if (n > 1511)
return false;
for (int i = n; i > n / 2; --i)
if (!s.contains(Integer.toBinaryString(i)))
return false;
return true;
}
}
// code provided by PROGIEZ
1016. Binary String With Substrings Representing 1 To N LeetCode Solution in Python
class Solution:
def queryString(self, s: str, n: int) -> bool:
if n > 1511:
return False
for i in range(n, n // 2, -1):
if format(i, 'b') not in s:
return False
return True
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.