Lonely Integer

  • Given an integer array where each number occurs twice except for one, find the unique (to rule them all?)

The point:

  • xor all elements together

Complexity :

Time Space
O(nlog(n)) O(1)
  • O(nlog(n)) in time because for each integer from 0 to n, counting the number of bits set is in log(n) => n log(n)
  • O(1) in space because in place

About Rust :

fn lonely_integer(nums : &[i32]) -> i32{
    let mut res = 0;
    // xor each element of the array
    // duplicate values cancel each other out (x^x=0)
    for num in nums{
        res ^=num;
    }
    // res store the lonely i32 because it is not canceled by any duplicate
    res
}

fn main() { // no main() if this code runs in a Jupyter cell 
    let nums = vec![1,3,3,2,1];
    println!("{}", lonely_integer(&nums)); // 2
} // end of local scope OR end of main()

Back to top

Published on: Jun 22 2025 at 09:00 AM | Last updated: Jun 22 2025 at 09:00 AM

Copyright © 1964-2025 - 40tude