Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.
Example 1:
Input: s = "00110110", k = 2 Output: true Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.
Example 2:
Input: s = "0110", k = 1 Output: true Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring.
Example 3:
Input: s = "0110", k = 2 Output: false Explanation: The binary code "00" is of length 2 and does not exist in the array.
Constraints:
1 <= s.length <= 5 * 105s[i] is either '0' or '1'.1 <= k <= 20This approach uses a set to store all unique substrings of length k encountered in s. By sliding a window of size k across the string, we add each substring to the set. If the set size equals 2^k, return true because all possible binary strings of length k are present. Otherwise, return false.
The function utilizes a set to keep track of unique substrings of length k. Iterating over the string from index 0 to len(s)-k, each k-length substring is added to the set. If the set's size becomes 2^k, we know all binary codes of length k are present in s. The operation seen.add(substring) ensures unique tracking, while len(seen) == 2**k quickly checks the condition to return true.
Java
JavaScript
Time Complexity: O(n * k) where n is the length of the string,
Space Complexity: O(min(2^k, n)), primarily due to the set storing at most 2^k elements.
This approach improves efficiency by using bit manipulation instead of storing full substrings. Treat the k-length binary strings as numbers and update a rolling number using bitmasking while sliding over string s. This can detect all variations without explicitly storing them.
The C solution utilizes a boolean array to represent the presence of each binary code of length k. By treating binary codes as integers and updating a rolling hash (a bitmask method shifting left and masking), it determines uniqueness with minimal space. Each k-length sequence is translated into this integer representation, tracked via the boolean array.
C++
C#
Time Complexity: O(n),
Space Complexity: O(2^k), primarily determined by the boolean tracking array.
| Approach | Complexity |
|---|---|
| Bitmask with Set | Time Complexity: O(n * k) where n is the length of the string, |
| Sliding Window with Bitmask | Time Complexity: O(n), |
Check if a String Contains all Binary Codes of Size K - Leetcode 1461 - Python • NeetCode • 18,295 views views
Watch 9 more video solutions →Practice Check If a String Contains All Binary Codes of Size K with our built-in code editor and test cases.
Practice on FleetCode