Check If a String Contains All Binary Codes of Size K LeetCode solution in C++

1
class Solution {
2
public:
3
bool hasAllCodes(string s, int k) {
4
int n = pow(2, k), m = s.size();
5
vector<bool> check(n, 0); // Check Array ,initially all value false;
6

7
int val = 0; // Variable that will help in formation of binary to decimal
8
// value of every substring.
9
int i = 0, j = 0; // Sliding window ponter.
10

11
while (j < m) {
12
val = val * 2 + (s[j] - '0'); // Form Binary ,Make it decimal.
13

14
if (j - i + 1 < k) // If window size is Less than k ,just j++;
15
j++;
16
else if (j - i + 1 == k) // If we hit k size.
17
{
18
check[val] = true; // Mark check cval true.
19
val = val - (s[i] - '0') * (pow(2, k - 1)); // Remove ith value's Calucaltion .
20
i++; // Increment i
21
j++; // and Increment j to maintain size of window as k
22
}
23
}
24

25
for (int l = 0; l < n; l++) {
26
if (check[l] == false) // If we didn't find any value ,means that susbtring is missing
27
return false; // Return false;
28
}
29

30
return true; // Return true;
31
}
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0