LeetCode solutions

2656. Count the Number of Beautiful Subarrays

My accepted Python solution to LeetCode problem 2656, Count the Number of Beautiful Subarrays, running in 122ms.

  • Difficulty: Medium
  • Python
  • Runtime 122ms
  • Memory 40.4MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 122ms, memory 40.4MB, accepted 2025-12-31.

python
class Solution:
    def beautifulSubarrays(self, nums: List[int]) -> int:
        from collections import defaultdict
        
        # A subarray is beautiful if XOR of all elements is 0
        # XOR[i:j] = 0 means prefix_xor[i] == prefix_xor[j+1]
        # Count pairs with same prefix XOR
        
        prefix_xor = 0
        count_map = defaultdict(int)
        count_map[0] = 1  # Empty prefix has XOR 0
        
        result = 0
        
        for num in nums:
            prefix_xor ^= num
            result += count_map[prefix_xor]
            count_map[prefix_xor] += 1
        
        return result

Source