Count the Number of Beautiful Subarrays - Prefix Bitmasks & Hashmap [JS]

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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]