find the kth least frequent element in an array in rust

To find the kth least frequent element in an array, we can use a hash table to store the frequency of each element in the array. After that, we can sort those frequencies and get the kth least frequent element.

Here's the Rust code:

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

fn kth_least_frequent(arr: &[i32], k: usize) -> Option<i32> {
    let mut map = HashMap::new();
    for &num in arr {
        *map.entry(num).or_insert(0) += 1;
    }
    
    let mut freq = map.values().collect::<Vec<_>>();
    freq.sort();
    
    if k > freq.len() {
        None
    } else {
        let kth_freq = freq[freq.len()-k];
        map.iter().find(|&(_, &v)| v == *kth_freq).map(|(&k, _)| k)
    }
}

fn main() {
    let arr = [1, 5, 4, 5, 4, 4, 2, 2, 2];
    let k = 2;
    let result = kth_least_frequent(&arr, k);
    if let Some(num) = result {
        println!("The {}th least frequent element is {}", k, num);
    } else {
        println!("Invalid k value");
    }
}
722 chars
30 lines

In this code, we create a HashMap to store the frequency of each element in the array. Then, we collect the frequency values into a Vec, sort it, and find the kth least frequent element in the original hash map. If the k value is invalid, i.e., greater than the length of the frequency vector, the function returns None. Finally, we print the result to the console.

gistlibby LogSnag