Skip to main content
Back to problems
#2997
Medium Algorithms

Minimum number of operations to make array xor equal to k

Array Bit Manipulation
85.5% acceptance
Feb 25, 2026
621
61
You are given a 0-indexed integer array nums and a positive integer k. You can apply the following operation on the array any number of times: 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. Return the minimum number of operations required to make the bitwise XOR of all elements of the final array equal to k. 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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(nums: Vec<i32>, k: i32) -> i32 {
    // Current XOR of all elements
    let current_xor = nums.iter().fold(0i32, |acc, &x| acc ^ x);
    // Bits that differ between current_xor and k must each be flipped once
    (current_xor ^ k).count_ones() as i32
  }
}