[LeetCode] Count the Number of Beautiful Subarrays

2588. Count the Number of Beautiful Subarrays

You are given a 0-indexed integer array nums. In one operation, you can:

  • Choose two different indices i and j such that 0 <= i, j < nums.length.
  • Choose a non-negative integer k such that the kth bit (0-indexed) in the binary representation of nums[i] and nums[j] is 1.
  • Subtract 2k from nums[i] and nums[j].

A subarray is beautiful if it is possible to make all of its elements equal to 0 after applying the above operation any number of times.

Return the number of beautiful subarrays in the array nums.

A subarray is a contiguous non-empty sequence of elements within an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
long long beautifulSubarrays(vector<int>& nums) {
long long bit = 0, res = 0;
unordered_map<long long, long long> freq{{0,1}};
for(auto n : nums) {
bit ^= n;
if(freq.count(bit)) res += freq[bit];
freq[bit] += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/03/12/PS/LeetCode/count-the-number-of-beautiful-subarrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.