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

Beautiful Towers II - Monotonic Increasing Stack [JS]

Check if There is a Valid Partition For The Array - Two Approaches - DP & Recursion w/ Memoization [JS]

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Count Elements With Maximum Frequency - Hashmap [JS]

Divide Nodes Into the Maximum Number of Groups - Union Find & BFS [JS]