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

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

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

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

Sum of Prefix Scores of Strings - Trie [JS]