SwiftSnippetRustProgrammingAlgorithm
Last updated at 2023-08-01

Algorithm Test: Odd Occurrences In Array

ClickUp
Note
AI Status
Last Edit By
Last edited time
Aug 1, 2023 04:28 AM
Metatag
Slug
algorithm-test-odd-occurences-in-array
Writer
Published
Published
Date
Jul 30, 2023
Category
Swift
Snippet
Rust
Programming
Algorithm
🚨
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

  1. [2]
  1. [2, 2, 3]
  1. [2, 2, 4, 1, 1]

Example Output

  1. 2
  1. 3
  1. 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() }

Discussion (0)

Related Posts