Leetcode 1461: Check If a String Contains All Binary Codes of Size K

grid47
grid47
Exploring patterns and algorithms
Jun 13, 2024 6 min read

You are given a binary string s and an integer k. Your task is to determine if every possible binary code of length k appears as a substring within s. Return true if all such binary codes are present, otherwise return false.
Problem
Approach
Steps
Complexity
Input: The input consists of a binary string s and an integer k, where s represents a binary number and k specifies the length of binary codes to check.
Example: Input: s = "1101011", k = 2
Constraints:
• 1 <= s.length <= 5 * 10^5
• s[i] is either '0' or '1'.
• 1 <= k <= 20
Output: Return true if every possible binary code of length k exists as a substring of s. Otherwise, return false.
Example: Output: true
Constraints:
• The output is a boolean value indicating whether every binary code of length k exists in the string.
Goal: Check if all binary codes of length k are present as substrings of s.
Steps:
• Initialize a set to store the binary codes of length k that appear as substrings.
• Iterate over the string s, checking each substring of length k.
• For each substring, add it to the set.
• If the set size equals 2^k, then all possible binary codes of length k have been found.
Goal: The conditions that input values must satisfy.
Steps:
• The length of s is at most 500,000 characters, so the solution must be efficient.
• k is at most 20, so there are at most 2^k possible binary codes to check.
Assumptions:
• The input string s is valid and contains only '0' and '1'.
• The integer k is at most 20, ensuring that checking all binary codes of length k is feasible.
Input: Input: s = "00110110", k = 2
Explanation: Output: true. The binary codes of length 2 are "00", "01", "10", and "11", and all of them appear as substrings in s.

Input: Input: s = "0110", k = 1
Explanation: Output: true. The binary codes of length 1 are "0" and "1", and both appear as substrings in s.

Input: Input: s = "0110", k = 2
Explanation: Output: false. The binary code "00" is missing as a substring in s.

Link to LeetCode Lab


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