How to group elements of an array based on their first occurrence in Rust

1 Answer

0 votes
const MAX_VALUE: usize = 100;

fn group_elements(arr: &[usize]) -> Vec<usize> {
    let mut frequency = [0; MAX_VALUE];
    let mut order = Vec::new();
    let mut result = Vec::new();

    // Count frequencies and track order of first occurrences
    for &num in arr {
        if frequency[num] == 0 {
            order.push(num);
        }
        frequency[num] += 1;
    }

    // Group elements based on their first occurrence
    for &num in &order {
        for _ in 0..frequency[num] {
            result.push(num);
        }
    }

    result
}

fn main() {
    let arr = [88, 33, 77, 88, 22, 55, 88, 55, 11, 99, 88, 11, 77];
    let grouped = group_elements(&arr);

    print!("Grouped vector: ");
    for num in grouped {
        print!("{} ", num);
    }
}



/*
run:

Grouped vector: 88 88 88 88 33 77 77 22 55 55 11 11 99 

*/

 



answered Oct 11, 2025 by avibootz
...