Skip to content

Commit

Permalink
Added single number II solution
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Nov 26, 2024
1 parent 34f72ca commit 89f5fb7
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,8 @@ programming challenges completed in other languages.
- [Take K Characters From Left and Right](https://leetcode.com/problems/take-k-of-each-character-from-left-and-right)
- [Unguarded Cells](https://leetcode.com/problems/count-unguarded-cells-in-the-grid)
- [Rotate the Box](https://leetcode.com/problems/rotating-the-box)
- [Find Champion](https://leetcode.com/problems/find-champion-ii/)
- [Find Champion II](https://leetcode.com/problems/find-champion-ii/)
- [Single Number II](https://leetcode.com/problems/find-champion-ii/)

#### Hard

Expand Down
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,4 @@ mod make_increasing;
mod rotate_box;
mod find_champion;
mod single_number;
mod single_number_ii;
27 changes: 27 additions & 0 deletions src/leetcode/single_number_ii.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use std::collections::HashMap;

pub fn single_number(numbers: Vec<i32>) -> i32 {
let counter = numbers.into_iter().fold(HashMap::new(), |mut acc, curr| {
*acc.entry(curr).or_insert(0) += 1;
acc
});
counter.into_iter().find(|(_, v)| *v == 1).unwrap().0
}

// Optimized solution
// Credit: https://leetcode.com/problems/single-number-ii/solutions/2389678/rust-concise-solution-with-ternary-logic-explained/
// pub fn single_number(numbers: Vec<i32>) -> i32 {
// numbers
// .into_iter()
// .fold([0, 0], |[a, b], x| [a ^ x & !b, a & x | b & !x])[0]
// }

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn finds_the_number_that_appears_once() {
assert_eq!(3, single_number(vec![2, 2, 3, 2]));
}
}

0 comments on commit 89f5fb7

Please sign in to comment.