Count the Number of Beautiful Subarrays — LeetCode 2588 Python Solution

MediumBit ManipulationArrayHash TablePrefix Sum
Problem
#2588
Pattern
Prefix Sum
Reading time
2 min

The 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.

Example

Input
nums = [4,3,1,2,4]
Output
2
Explanation
There are 2 beautiful subarrays in nums: [4,3,1,2,4] and [4,3,1,2,4].

Python solution

Python
class Solution:
    def beautifulSubarrays(self, nums: List[int]) -> int:
        cnt = Counter({0: 1})
        ans = mask = 0
        for x in nums:
            mask ^= x
            ans += cnt[mask]
            cnt[mask] += 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2588. Count the Number of Beautiful Subarrays is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2588. Count the Number of Beautiful Subarrays?
LeetCode 2588. Count the Number of Beautiful Subarrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 2588. Count the Number of Beautiful Subarrays?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2588. Count the Number of Beautiful Subarrays?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2588. Count the Number of Beautiful Subarrays cover?
LeetCode 2588. Count the Number of Beautiful Subarrays is tagged Bit Manipulation, Array, Hash Table and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview