#1461
Medium Algorithms Check if a string contains all binary codes of size k
Hash Table String Bit Manipulation Rolling Hash Hash Function
61.5% acceptance
Feb 25, 2026
2709
116
Given a binary string s and an integer k, return true if every binary code of length k is a substring of s,
or false otherwise.
Solution
Rust
Time O(n)
Space O(n)
use std::collections::HashSet;
impl Solution {
pub fn has_all_codes(s: String, k: i32) -> bool {
let k = k as usize;
let need = 1usize << k;
if s.len() < k { return false; }
let mut seen = HashSet::new();
for i in 0..=(s.len() - k) {
seen.insert(&s[i..i + k]);
if seen.len() == need { return true; }
}
seen.len() == need
}
}