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 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 2^k 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 (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
Beautiful Subarrays: XOR = 0 Means All Bits Can Be Paired424231[4,2,4,2] XOR = 0 ✓[2] ✓[4] ✓[3,1] XOR = 0 ✓Beautiful subarrays have XOR = 0This means all bits can be paired and eliminated using allowed operationsTotal Beautiful Subarrays: 8
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
Asked in
Google 12 Microsoft 8 Amazon 6
23.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen