Bitwise ORs of Subarrays LeetCode solution in JavaScript

1
/** https://leetcode.com/problems/bitwise-ors-of-subarrays/
2
* @param {number[]} arr
3
* @return {number}
4
*/
5
var subarrayBitwiseORs = function (arr) {
6
// Hashset to store the unique bitwise
7
this.uniqueBw = new Set();
8

9
// Dynamic programming
10
dp(arr, arr.length - 1);
11

12
return this.uniqueBw.size;
13
};
14

15
var dp = function (arr, currIdx) {
16
// Base, reach beginning of the array
17
if (currIdx === 0) {
18
// Store the value to unique bitwise, since it's only single number, we store the actual value
19
this.uniqueBw.add(arr[0]);
20

21
// Return array
22
return [arr[0]];
23
}
24

25
// DP to previous index
26
let prev = dp(arr, currIdx - 1);
27

28
// Number at current index
29
let firstBw = arr[currIdx];
30

31
// Add number at current index to hashset, since it's only single number, we store the actual value
32
this.uniqueBw.add(firstBw);
33

34
// Another hashset to store the result of bitwise operation between number at current index with result from previous index
35
let currRes = new Set();
36
currRes.add(firstBw);
37

38
// Loop through result form previous index
39
for (let i = 0; i < prev.length; i++) {
40
// Perform bitwise operation OR
41
let curr = arr[currIdx] | prev[i];
42

43
// Add to unique bitwise collection
44
this.uniqueBw.add(curr);
45

46
// Add to current result
47
currRes.add(curr);
48
}
49

50
// Return current result as an array
51
return [...currRes];
52
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0