NeetCode #128LC-1461MediumArrays & Hashing
← Back to All Problems#128 · #1461 · Check If a String Contains All Binary Codes of Size K(检查一个字符串是否包含所有长度为 K 的二进制子串)
📌 Problem Statement & Constraints
Given a binary string
s and an integer k, return true if every binary code of length k appears as a substring of s. Constraints: 1 <= s.length <= 5 * 10^5, 1 <= k <= 20.💡 Core Algorithmic Approaches
- There are exactly
2^kdistinct binary strings of lengthk. - Collect all substrings of length
kinto a set and check whether its size equals2^k. - The bound
k <= 20keeps2^kat about a million, which is manageable. - A necessary condition is
len(s) >= 2^k + k - 1, since that is the minimum length of a de Bruijn sequence containing every code -- a useful early exit.
💻 Benchmark Python3 Implementation
class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
if len(s) < k:
return False
seen = {s[i:i + k] for i in range(len(s) - k + 1)}
return len(seen) == (1 << k) # 2^k distinct codes needed
# Early-exit variant: the theoretical minimum length rules out many inputs at once
class Solution2:
def hasAllCodes(self, s: str, k: int) -> bool:
if len(s) < (1 << k) + k - 1: # de Bruijn lower bound
return False
seen = {s[i:i + k] for i in range(len(s) - k + 1)}
return len(seen) == (1 << k)⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n * k) with the direct set construction (each substring slice costs O(k)), or O(n) with a rolling integer hash. The early-exit variant often returns in O(1).
💾 Space Complexity
O(2^k) for the set of codes, which is at most about a million entries.
⚠️ Interview Pitfalls & Follow-ups
- Using
range(len(s) - k): the last substring is missed; the bound islen(s) - k + 1. - Checking
len(seen) >= 2^k: it can never exceed2^k, so==is the right test (and>=would be equivalent but misleading). - Forgetting the
len(s) < kguard: the slice range would be empty and the set would be empty, so it would returnFalseanyway -- but the guard makes the intent explicit. - Assuming
kcan be large:k <= 20is what makes enumerating all2^kcodes feasible.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
检查一个字符串是否包含所有长度为 K 的二进制子串
给你一个二进制字符串 s 和一个整数 k。如果所有长度为 k 的二进制字符串都是 s 的子串,请返回 true,否则返回 false。约束:1 ≤ s.length ≤ 5 × 10^5;1 ≤ k ≤ 20;s[i] 为 0 或 1。
核心要点
- 滑窗收集所有子串(标准解) :长度为 k 的二进制串共有 2^k 个。用集合收集 s 中所有长度为 k 的子串,若集合大小达到 2^k 则返回 True。
- 提前退出的必要性 : 2^k 在 k = 20 时约为 100 万,而 s 的长度上界是 5 × 10^5,因此 k > 19 时必然不可能包含全部——集合大小达到 2^k 时立即返回可省去后续扫描。
- 剪枝 :若 len(s) < k + 2^k - 1 (包含全部 2^k 个串所需的最小长度),可直接返回 False。
- 进阶优化 · 滚动位编码 :把子串编码为 k 位整数,用滚动方式 O(1) 更新(左移一位、按位与掩码、加新位),避免每次切片。
常见陷阱
- 不提前返回 : 2^k 可达 10^6,虽然本题规模下仍可接受,但缺少提前退出会多扫一遍。
- 遍历范围写成 range(len(s) - k) :会漏掉最后一个窗口。应为 range(len(s) - k + 1) 。
- 忘记 len(s) - k + 1 < need 的剪枝 :不剪枝也能得到正确答案(集合大小自然达不到 need),但剪枝更清晰。
- 误以为 2^k 需要真正枚举出来 :只需比较集合大小与 2^k ,无需构造所有可能的二进制串。
参考实现
class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
need = 1 << k # 共 2^k 个长度为 k 的二进制串
if len(s) - k + 1 < need: # 子串总数不足,必然不满足
return False
seen = set()
for i in range(len(s) - k + 1):
seen.add(s[i:i + k])
if len(seen) == need: # 全部集齐,提前返回
return True
return False