2997. Minimum Number of Operations to Make Array XOR Equal to K Medium
1/**
2 * [2997] Minimum Number of Operations to Make Array XOR Equal to K
3 *
4 * You are given a 0-indexed integer array nums and a positive integer k.
5 * You can apply the following operation on the array any number of times:
6 *
7 * Choose any element of the array and flip a bit in its binary representation. Flipping a bit means changing a 0 to 1 or vice versa.
8 *
9 * Return the minimum number of operations required to make the bitwise XOR of all elements of the final array equal to k.
10 * Note that you can flip leading zero bits in the binary representation of elements. For example, for the number (101)2 you can flip the fourth bit and obtain (1101)2.
11 *
12 * <strong class="example">Example 1:
13 *
14 * Input: nums = [2,1,3,4], k = 1
15 * Output: 2
16 * Explanation: We can do the following operations:
17 * - Choose element 2 which is 3 == (011)2, we flip the first bit and we obtain (010)2 == 2. nums becomes [2,1,2,4].
18 * - Choose element 0 which is 2 == (010)2, we flip the third bit and we obtain (110)2 = 6. nums becomes [6,1,2,4].
19 * The XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k.
20 * It can be shown that we cannot make the XOR equal to k in less than 2 operations.
21 *
22 * <strong class="example">Example 2:
23 *
24 * Input: nums = [2,0,2,0], k = 0
25 * Output: 0
26 * Explanation: The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed.
27 *
28 *
29 * Constraints:
30 *
31 * 1 <= nums.length <= 10^5
32 * 0 <= nums[i] <= 10^6
33 * 0 <= k <= 10^6
34 *
35 */
36pub struct Solution {}
37
38// problem: https://leetcode.com/problems/minimum-number-of-operations-to-make-array-xor-equal-to-k/
39// discuss: https://leetcode.com/problems/minimum-number-of-operations-to-make-array-xor-equal-to-k/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42
43impl Solution {
44 pub fn min_operations(nums: Vec<i32>, k: i32) -> i32 {
45 0
46 }
47}
48
49// submission codes end
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 #[test]
56 fn test_2997() {
57 }
58}
59
Back
© 2025 bowen.ge All Rights Reserved.