Count the Number of Beautiful Subarrays - Problem
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 thekth bit (0-indexed) in the binary representation ofnums[i]andnums[j]is 1. - 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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [4,2,4,2,3,1]
›
Output:
8
💡 Note:
Beautiful subarrays: [4,2,4,2], [2,4], [4,2], [2,4,2,3,1], [2], [4], [2], [3,1]. All have XOR = 0, meaning all bits can be paired and eliminated.
Example 2 — Single Elements
$
Input:
nums = [1,10,4]
›
Output:
0
💡 Note:
No subarrays have XOR = 0. Each single element has non-zero XOR, and combinations like [1,10], [10,4], [1,10,4] all have non-zero XOR.
Example 3 — All Zeros
$
Input:
nums = [0,0,0]
›
Output:
6
💡 Note:
All subarrays are beautiful since they contain only zeros: [0], [0], [0], [0,0], [0,0], [0,0,0]. Each has XOR = 0.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Given array with integer elements
2
Find XOR = 0
Identify subarrays where XOR of all elements equals 0
3
Count Beautiful
Count all such subarrays as beautiful
Key Takeaway
🎯 Key Insight: A subarray is beautiful if its XOR equals 0, enabling perfect bit pairing
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code