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
Count Beautiful Subarrays INPUT nums array: 4 i=0 2 i=1 4 i=2 2 i=3 3 i=4 1 i=5 Binary Values: 4 = 100 2 = 010 3 = 011 4 = 100 2 = 010 1 = 001 Beautiful Subarray: XOR of all elements = 0 (pairs cancel each bit) Length: 6 elements ALGORITHM STEPS 1 Init prefix XOR map map[0] = 1, xor = 0 2 Running XOR xor = xor ^ nums[i] 3 Count matches count += map[xor] 4 Update map map[xor]++ Running XOR Trace: i | num | xor | map[xor] | count - | - | 0 | 1 | 0 0 | 4 | 4 | 0 | 0 1 | 2 | 6 | 0 | 0 2 | 4 | 2 | 0 | 0 3 | 2 | 0 | 1 | 1 4 | 3 | 3 | 0 | 1 5 | 1 | 2 | 1 | 2 ... more iterations ... FINAL RESULT Beautiful Subarrays Found: 8 Example Subarrays: [4,2,4,2] XOR=0 OK [2,4,2,3,1] XOR=0 OK [4,2,4,2,3,1] XOR=0 OK [4,2,4,2] XOR=0 OK [2,4,2] XOR=0 OK [3,1] XOR=2 (pair bits) ... and 3 more Output: 8 Key Insight: A subarray is beautiful if XOR of all elements equals 0. Using prefix XOR, if prefix[j] = prefix[i], then XOR(i+1...j) = 0. Count pairs with same prefix XOR using a HashMap for O(n) solution. Time: O(n) | Space: O(n) - Much better than O(n^2) brute force checking all subarrays. TutorialsPoint - Count the Number of Beautiful Subarrays | Running XOR Approach
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