Skip to main content
Back to problems
#3158
Easy Algorithms

Find the xor of numbers which appear twice

Array Hash Table Bit Manipulation
78.8% acceptance
Feb 24, 2026
165
14
You are given an array nums, where each number in the array appears either once or twice. Return the bitwise XOR of all the numbers that appear twice in the array, or 0 if no number appears twice.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn duplicate_numbers_xor(nums: Vec<i32>) -> i32 {
    let mut seen = 0u64;
    let mut result = 0i32;
    for &x in &nums {
      if seen & (1u64 << x) != 0 {
        result ^= x;
      }
      seen |= 1u64 << x;
    }
    result
  }
}