432. All O`one Data Structure

Implement a data structure supporting the following operations:

  1. Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string.
  2. Dec(Key) - If Key's value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this function does nothing. Key is guaranteed to be a non-empty string.
  3. GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "".
  4. GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string "".

Challenge: Perform all these in O(1) time complexity.

Rust Solution

use std::collections::HashMap;

struct AllOne {
    dict: HashMap<String, usize>,
}

impl AllOne {
    fn new() -> Self {
        let dict = HashMap::new();
        AllOne { dict }
    }

    fn inc(&mut self, key: String) {
        self.dict.entry(key).and_modify(|v| *v += 1).or_insert(1);
    }

    fn dec(&mut self, key: String) {
        if !self.dict.contains_key(&key) {
            return;
        }
        if self.dict[&key] == 1 {
            self.dict.remove(&key);
        } else {
            *self.dict.get_mut(&key).unwrap() -= 1;
        }
    }

    fn get_max_key(&mut self) -> String {
        self.dict
            .iter()
            .max_by_key(|(_, &v)| v)
            .unwrap_or((&String::from(""), &0))
            .0
            .to_string()
    }

    fn get_min_key(&mut self) -> String {
        self.dict
            .iter()
            .min_by_key(|(_, &v)| v)
            .unwrap_or((&String::from(""), &0))
            .0
            .to_string()
    }
}

#[test]
fn test() {
    let mut obj = AllOne::new();
    obj.inc("abc".to_string());
    assert_eq!(obj.get_max_key(), "abc".to_string());
}

Having problems with this solution? Click here to submit an issue on github.