#2588

Count the Number of Beautiful Subarrays

Medium
ArrayHash TableBit ManipulationPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses the prefix XOR technique to efficiently count beautiful subarrays. By maintaining a count of prefix XOR values, we can determine how many times a specific XOR value has occurred, allowing us to find subarrays with an XOR of zero quickly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a hashmap to store the frequency of prefix XOR values and a variable for the current prefix XOR.
  2. 2Step 2: Iterate through the array, updating the prefix XOR with each element.
  3. 3Step 3: For each prefix XOR, check if it has been seen before. If yes, add its frequency to the count of beautiful subarrays.
  4. 4Step 4: If the prefix XOR is zero, increment the count as it indicates a beautiful subarray from the start.
  5. 5Step 5: Update the hashmap with the current prefix XOR frequency.
solution.py9 lines
1def countBeautifulSubarrays(nums):
2    prefix_xor = 0
3    count = 0
4    xor_count = {0: 1}
5    for num in nums:
6        prefix_xor ^= num
7        count += xor_count.get(prefix_xor, 0)
8        xor_count[prefix_xor] = xor_count.get(prefix_xor, 0) + 1
9    return count

Complexity note: The time complexity is O(n) because we traverse the array once. The space complexity is O(n) due to the hashmap storing the prefix XOR frequencies.

  • 1A subarray is beautiful if its XOR is zero.
  • 2Using prefix XOR allows for efficient counting of beautiful subarrays.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.