LeetCode in Kotlin

2588. Count the Number of Beautiful Subarrays

Medium

You are given a 0-indexed integer array nums. In one operation, you can:

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.

Return the number of beautiful subarrays in the array nums.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

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

Example 2:

Input: nums = [1,10,4]

Output: 0

Explanation: There are no beautiful subarrays in nums.

Constraints:

Solution

class Solution {
    fun beautifulSubarrays(nums: IntArray): Long {
        val map = mutableMapOf<Int, Int>()
        map[0] = 1
        var res = 0L
        var sum = 0
        for (v in nums) {
            sum = sum xor v
            val count = map.getOrDefault(sum, 0)
            res += count
            map[sum] = count + 1
        }
        return res
    }
}