LeetCode No. 2588 - Counting the Number of Beautiful Subarrays - Python Implementation - Graphical Ideas and Hand-Torn Code

LeetCode No. 2588 - Counting the Number of Beautiful Subarrays - Python Implementation - Graphical Ideas and Hand-Torn Code


1. Topic description

insert image description here

2. Problem-solving ideas and code implementation

1. Problem-solving ideas

A beautiful sub-array is that the XOR sum of all elements in the sub-array is 0, which is not difficult to understand. If there is only an even number of digits that are not 0, then the result of the XOR is 0. If the odd number is not 0, the result That's 1.

We can find the XOR sum of the sub-arrays from 0 to i, that is, the prefix XOR sum. If there are two prefix XOR sums that are the same, that is, the prefix XOR sums of 0-i and 0-j are the same, then ij The XOR sum of is 0, which is not difficult to understand, because the part 0-i is repeated twice.

So we first find the prefix XOR sum, then add one to the same element, and finally return the result.

2. Code implementation

The code is as follows (example):

class Solution:
    def beautifulSubarrays(self, nums: List[int]) -> int:
        prefix=[0]
        for i in nums:
            prefix.append(i ^ prefix[-1])
        
        cnt=Counter()
        res=0
        for x in prefix:
            res+=cnt[x]
            cnt[x]+=1
        return res

Among them, you can output the prefix XOR and take a look

输入:
[4,3,1,2,4]
输出:
[0, 4, 7, 6, 4, 0]

Summarize

The difficulty of this question is to understand how to convert the problem into the solution of the number of prefix XOR sums.

Guess you like

Origin blog.csdn.net/weixin_45271005/article/details/129538430