find the kth most common element in an array in rust

One way to find the kth most common element in an array in Rust is by using a HashMap to count the frequency of elements in the array, sorting the HashMap entries by frequency, and returning the kth entry. Here's an example implementation:

main.rs
use std::collections::HashMap;

fn kth_most_common_element(arr: &[i32], k: usize) -> Option<&i32> {
    // count frequency of elements in array
    let mut freq_map = HashMap::new();
    for &num in arr {
        *freq_map.entry(num).or_insert(0) += 1;
    }

    // sort HashMap entries by frequency
    let mut freq_vec: Vec<_> = freq_map.into_iter().collect();
    freq_vec.sort_by_key(|x| x.1);
    freq_vec.reverse();

    // return kth most common element if it exists
    freq_vec.get(k - 1).map(|x| x.0)
}

fn main() {
    let arr = [1, 2, 3, 3, 3, 4, 4, 5];
    let k = 2;
    let kth_most_common = kth_most_common_element(&arr, k);
    if let Some(num) = kth_most_common {
        println!("{}th most common element is {}", k, num);
    } else {
        println!("Array has less than {} distinct elements", k);
    }
}
829 chars
29 lines

In the example above, we first count the frequency of elements in the arr array using a HashMap. We then convert the HashMap into a Vec of (element, frequency) tuples, sort the Vec in descending order of frequency, and return the kth element if it exists.

Note that if the array has less than k distinct elements, the function will return None.

gistlibby LogSnag