Is there any max or min function for finding the maximum or minimum in a HashSet<u32> in rust

how can i find the maximum or minimum value in a HashSet without looping through all the elements in it?

You cannot, because HashSet is by definition unordered. If you need this operation often it may be better to use another type of data structure such as BTreeSet or even a sorted Vec, depending on your other constraints.

11 Likes

If you never remove elements from the HashSet, you could store the maximum and minimum next to the set.

use std::collections::HashSet;

pub struct IntSet {
    set: HashSet<u32>,
    max: u32,
}

impl IntSet {
    pub fn new() -> Self {
        Self {
            set: HashSet::new(),
            max: 0,
        }
    }
    
    pub fn insert(&mut self, value: u32) {
        if value > self.max {
            self.max = value;
        }
        self.set.insert(value);
    }
    
    pub fn contains(&self, value: u32) -> bool {
        self.set.contains(&value)
    }
    
    pub fn get_max(&self) -> u32 {
        self.max
    }
}
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.