Description
Solution: Prefix Bitmasks & Hashmap
Keep track of the running prefix bitmask as we go through nums.
Since we only need to know whether the number of 1 bits at each position is even or odd, we can use 0
to represent an even number of bits, and 1
to represent an odd number of bits.
For each index i
, count the number of previous prefix bitmasks with the exact same state as the current bitmask.
If the bitmasks are the same, that means each bit has an even count for the subarray between index i
and the previous bitmask.
Use a hashmap to count the occurances of each bitmask.
Time Complexity: O(n)
Space Complexity: O(n)
var beautifulSubarrays = function(nums) {
let mask = 0, count = new Map(), ans = 0;
count.set(0, 1);
for (let i = 0; i < nums.length; i++) {
mask = mask ^ nums[i];
ans += (count.get(mask) || 0);
count.set(mask, (count.get(mask) || 0) + 1);
}
return ans;
};
Comments
Post a Comment