2588. Count the Number of Beautiful Subarrays Medium
1/**
2 * [2588] Count the Number of Beautiful Subarrays
3 *
4 * You are given a 0-indexed integer array nums. In one operation, you can:
5 *
6 * Choose two different indices i and j such that 0 <= i, j < nums.length.
7 * Choose a non-negative integer k such that the k^th bit (0-indexed) in the binary representation of nums[i] and nums[j] is 1.
8 * Subtract 2^k from nums[i] and nums[j].
9 *
10 * 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.
11 * Return the number of beautiful subarrays in the array nums.
12 * A subarray is a contiguous non-empty sequence of elements within an array.
13 *
14 * <strong class="example">Example 1:
15 *
16 * Input: nums = [4,3,1,2,4]
17 * Output: 2
18 * Explanation: There are 2 beautiful subarrays in nums: [4,<u>3,1,2</u>,4] and [<u>4,3,1,2,4</u>].
19 * - We can make all elements in the subarray [3,1,2] equal to 0 in the following way:
20 * - Choose [<u>3</u>, 1, <u>2</u>] and k = 1. Subtract 2^1 from both numbers. The subarray becomes [1, 1, 0].
21 * - Choose [<u>1</u>, <u>1</u>, 0] and k = 0. Subtract 2^0 from both numbers. The subarray becomes [0, 0, 0].
22 * - We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:
23 * - Choose [<u>4</u>, 3, 1, 2, <u>4</u>] and k = 2. Subtract 2^2 from both numbers. The subarray becomes [0, 3, 1, 2, 0].
24 * - Choose [0, <u>3</u>, <u>1</u>, 2, 0] and k = 0. Subtract 2^0 from both numbers. The subarray becomes [0, 2, 0, 2, 0].
25 * - Choose [0, <u>2</u>, 0, <u>2</u>, 0] and k = 1. Subtract 2^1 from both numbers. The subarray becomes [0, 0, 0, 0, 0].
26 *
27 * <strong class="example">Example 2:
28 *
29 * Input: nums = [1,10,4]
30 * Output: 0
31 * Explanation: There are no beautiful subarrays in nums.
32 *
33 *
34 * Constraints:
35 *
36 * 1 <= nums.length <= 10^5
37 * 0 <= nums[i] <= 10^6
38 *
39 */
40pub struct Solution {}
41
42// problem: https://leetcode.com/problems/count-the-number-of-beautiful-subarrays/
43// discuss: https://leetcode.com/problems/count-the-number-of-beautiful-subarrays/discuss/?currentPage=1&orderBy=most_votes&query=
44
45// submission codes start here
46
47impl Solution {
48 pub fn beautiful_subarrays(nums: Vec<i32>) -> i64 {
49
50 }
51}
52
53// submission codes end
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58
59 #[test]
60 fn test_2588() {
61 }
62}
63
Back
© 2025 bowen.ge All Rights Reserved.