How to find the element with minimum occurrences in a vector with Rust

1 Answer

0 votes
use std::collections::HashMap;
use std::hash::Hash;

/// Finds the element with the minimum number of occurrences in a slice.
///
/// # Generics
/// * `T`: Must implement `Eq` and `Hash` to be stored in a `HashMap`, 
///   and `Clone` to return a copy of the value.
///
/// # Returns
/// * `Option<T>`: `Some(element)` containing the least frequent item, or `None` if the slice is empty.
pub fn min_occurrence<T>(slice: &[T]) -> Option<T>
where
    T: Eq + Hash + Clone,
{
    if slice.is_empty() {
        return None;
    }

    // 1. Tally element frequencies using HashMap and Entry API in O(N) time
    let mut counts = HashMap::with_capacity(slice.len());
    for item in slice {
        *counts.entry(item).or_insert(0usize) += 1;
    }

    // 2. Find the key with the minimum frequency count using iterator combinators
    counts
        .into_iter()
        .min_by_key(|&(_, count)| count)
        .map(|(item, _)| item.clone())
}

fn main() {
    let vec = vec![1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3];

    match min_occurrence(&vec) {
        Some(result) => println!("{result}"), // Output: 5
        None => println!("The slice was empty."),
    }
}


/*
run:

5

*/

 



answered Sep 26 by avibootz
...