Count the Number of Beautiful Subarrays Problem
Description
LeetCode Problem 2588.
You are given a 0-indexed integer array nums. In one operation, you can:
- Choose two different indices
iandjsuch that0 <= i, j < nums.length. - Choose a non-negative integer
ksuch that thek^thbit (0-indexed) in the binary representation ofnums[i]andnums[j]is1. - Subtract
2^kfromnums[i]andnums[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 (including zero).
Return the number of beautiful subarrays in the array nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Note: Subarrays where all elements are initially 0 are considered beautiful, as no operation is needed.
Example 1:
Input: nums = [4,3,1,2,4]
Output: 2
Explanation: There are 2 beautiful subarrays in nums: [4,3,1,2,4] and [4,3,1,2,4].
- We can make all elements in the subarray [3,1,2] equal to 0 in the following way:
- Choose [3, 1, 2] and k = 1. Subtract 2^1 from both numbers. The subarray becomes [1, 1, 0].
- Choose [1, 1, 0] and k = 0. Subtract 2^0 from both numbers. The subarray becomes [0, 0, 0].
- We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:
- Choose [4, 3, 1, 2, 4] and k = 2. Subtract 2^2 from both numbers. The subarray becomes [0, 3, 1, 2, 0].
- Choose [0, 3, 1, 2, 0] and k = 0. Subtract 2^0 from both numbers. The subarray becomes [0, 2, 0, 2, 0].
- Choose [0, 2, 0, 2, 0] and k = 1. Subtract 2^1 from both numbers. The subarray becomes [0, 0, 0, 0, 0].
Example 2:
Input: nums = [1,10,4]
Output: 0
Explanation: There are no beautiful subarrays in nums.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^6
Solution
Approach: Prefix XOR + Hash Table
A subarray can be turned into all zeros exactly when, for every bit position, the number of ones among its elements is even, that is, when the XOR of the subarray is 0.
The XOR of nums[i+1..j] is zero when the prefix XORs up to i and up to j are equal. So keep a hash table cnt of prefix XOR values (with 0 seen once at the start). For each element update the running mask, add cnt[mask] to the answer, then increase cnt[mask].
The time complexity is O(n) and the space complexity is O(n).
class Solution:
def beautifulSubarrays(self, nums: List[int]) -> int:
cnt = Counter({0: 1})
ans = mask = 0
for x in nums:
mask ^= x
ans += cnt[mask]
cnt[mask] += 1
return ans