You may find this algorithm test somewhere else. Because my source prohibits me from reproducing the question, I will just give you a question hint, and you will be presented with the solution.
The Question
There is an array contains odd number of elements that always paired except one unpaired.
Find the unpaired elements!
Example Input
- [2]
- [2, 2, 3]
- [2, 2, 4, 1, 1]
Example Output
- 2
- 3
- 4
The Solution
Swift
public func findUnpaired(_ array: [Int]) -> Int { var sets = Set<Int>() for el in array { if sets.contains(el) { sets.remove(el) } else { sets.insert(el) } } return sets.first! }
Advanced: Using XOR
XOR two equal number will result in zero.
0 == 2 ^ 2
public func findUnpaired(_ array: [Int]) -> Int { return array.reduce(0, ^) }
Rust
fn find_unpaired(array: &[i32]) -> i32 { let mut sets = std::collections::HashSet::new(); for el in array { if sets.contains(el) { sets.remove(el); } else { sets.insert(*el); } } *sets.iter().next().unwrap() }