Skip to content

Commit 92d166c

Browse files
authored
Create 3209-number-of-subarrays-with-and-value-of-k.js
1 parent 510f462 commit 92d166c

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
var countSubarrays = function (nums, k) {
7+
return atLeastK(nums, k) - atLeastK(nums, k + 1)
8+
}
9+
10+
function atLeastK(nums, k) {
11+
let ans = 0
12+
let temp = new Array(32).fill(0)
13+
14+
let l = 0
15+
for (let r = 0; r < nums.length; r++) {
16+
for (let i = 0; i < 32; i++) {
17+
if ((1 << i) & nums[r]) {
18+
temp[i]++
19+
}
20+
}
21+
22+
while (r - l + 1 > 0 && calc(temp, r - l + 1) < k) {
23+
for (let i = 0; i < 32; i++) {
24+
if ((1 << i) & nums[l]) {
25+
temp[i]--
26+
}
27+
}
28+
l++
29+
}
30+
ans += r - l + 1
31+
}
32+
33+
return ans
34+
}
35+
36+
// function to calculate the AND from frequency vector
37+
function calc(temp, w) {
38+
let ans = 0
39+
for (let i = 0; i < 32; i++) {
40+
if (temp[i] === w) {
41+
ans += 1 << i
42+
}
43+
}
44+
45+
return ans
46+
}

0 commit comments

Comments
 (0)