LeetCode 2588: Count the Number of Beautiful Subarrays Solution
Master LeetCode problem 2588 (Count the Number of Beautiful Subarrays), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2588. Count the Number of Beautiful Subarrays
Problem Explanation
Explanation:
To solve this problem, we can iterate through the array nums and maintain a hashmap to store the count of each prefix sum of the array. We will also keep track of the current prefix sum and the number of beautiful subarrays found so far.
For each element in the array, we update the current prefix sum by xor-ing it with the current element. Then, we iterate through all possible values of k (bits set to 1 in the binary representation of the prefix sum) and check if we have seen a prefix sum with the same k before. If we have, we increment the count of beautiful subarrays by the value stored in the map.
Finally, we update the map with the current prefix sum count and return the total count of beautiful subarrays found.
Time Complexity: O(N), where N is the length of the input array nums.
Space Complexity: O(N), for the hashmap used to store prefix sum counts.
:
Solution Code
class Solution {
public int countSubarrays(int[] nums) {
int n = nums.length;
int[] prefix = new int[n + 1];
int xor = 0;
int count = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
for (int i = 0; i < n; i++) {
xor ^= nums[i];
for (int k = 0; k < 20; k++) {
int target = xor ^ (1 << k);
count += map.getOrDefault(target, 0);
}
map.put(xor, map.getOrDefault(xor, 0) + 1);
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2588 (Count the Number of Beautiful Subarrays)?
This page provides optimized solutions for LeetCode problem 2588 (Count the Number of Beautiful Subarrays) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2588 (Count the Number of Beautiful Subarrays)?
The time complexity for LeetCode 2588 (Count the Number of Beautiful Subarrays) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2588 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2588 in Java, C++, or Python.