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

1
/**
2
* @param {string} s
3
* @param {number} k
4
* @return {boolean}
5
*/
6
var hasAllCodes = function (s, k) {
7
if (k > s.length) {
8
return false;
9
}
10

11
/* Max strings can be generated of k chars 0/1. */
12
const max = Math.pow(2, k);
13

14
/*
15
* Create a set.
16
* It will contain all unique values.
17
*/
18
const set = new Set();
19

20
for (let i = 0; i < s.length - k + 1; i++) {
21
/* Generate substring of size k from index i */
22
const substr = s.substr(i, k);
23
set.add(substr);
24

25
/*
26
* if enough of unique strings are generated,
27
* break the loop as there is no point of iterating
28
* as we have found all necessary strings.
29
*/
30
if (set.size === max) {
31
return true;
32
}
33
}
34

35
return set.size === max;
36
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0