Advertisement
1461. Check If a String Contains All Binary Codes of Size K
MediumView on LeetCode
Time: O(n)
Space: O(2^k)
Approach
Sliding window of length k with rolling bitwise update; mark each window value in a boolean array; check all 2^k are seen.
1461.cs
C#
// Approach: Sliding window of length k with rolling bitwise update; mark each window value in a boolean array; check all 2^k are seen.
// Time: O(n) Space: O(2^k)
public class Solution
{
public bool HasAllCodes(string s, int k)
{
int n = 1 << k;
if (s.Length < n)
return false;
bool[] used = new bool[n];
int window = k == 1 ? 0 : Convert.ToInt32(s.Substring(0, k - 1), 2);
for (int i = k - 1; i < s.Length; ++i)
{
window = (window << 1) + (s[i] - '0');
window &= n - 1;
used[window] = true;
}
return used.All(u => u);
}
}Advertisement
Was this solution helpful?