#260
Medium Algorithms Single number iii
Array Bit Manipulation
70.4% acceptance
Jan 12, 2026
6777
276
Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.
You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn single_number_iii(nums: Vec<i32>) -> Vec<i32> {
let xor = nums.iter().fold(0, |acc, &x| acc ^ x);
let diff_bit = xor & -xor;
let mut result = vec![0, 0];
for &num in &nums {
if num & diff_bit == 0 {
result[0] ^= num;
} else {
result[1] ^= num;
}
}
result
}
}