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]

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

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

Maximum Score After Applying Operations on a Tree - DFS [JS]

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