LeetCode Entry
1461. Check If a String Contains All Binary Codes of Size K
All numbers as substring length of k window
1461. Check If a String Contains All Binary Codes of Size K medium blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1278
Problem TLDR
All numbers as substring length of k #medium #sliding_window
Intuition
Use sliding window of k. Calculate the current number, add to a set. Uniqs count should be 2^k.
Approach
- use built-in windows, the k is small, can take substrings on the fly
- inverted solution: number of allowed duplicates is len-k+1 - 2^k
- return early
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(n)\)
Code
// 130ms
fun hasAllCodes(s: String, k: Int) =
s.windowed(k).toSet().size == 1 shl k
// 87ms
pub fn has_all_codes(s: String, k: i32) -> bool {
s.as_bytes().windows(k as usize).unique().count() as i32 == 1 << k
}