From 873e50b5996860918de00b51b93123aac534df6b Mon Sep 17 00:00:00 2001 From: Ashish Chauhan <119170180+Ash914027@users.noreply.github.com> Date: Wed, 2 Oct 2024 11:54:31 +0530 Subject: [PATCH] Create ALL_in_One_datastructure.cpp --- ALL_in_One_datastructure.cpp | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 ALL_in_One_datastructure.cpp diff --git a/ALL_in_One_datastructure.cpp b/ALL_in_One_datastructure.cpp new file mode 100644 index 0000000..ee74c77 --- /dev/null +++ b/ALL_in_One_datastructure.cpp @@ -0,0 +1,47 @@ +class AllOne { +public: + unordered_map count; // Stores the count of each key + set> se; // Sorted set to keep counts and keys + + AllOne() { + count.clear(); // Initialize the count map + } + + // Increment the count of the key + void inc(string key) { + int n = count[key]; // Get current count + count[key]++; // Increment the count + se.erase({n, key}); // Remove the old pair from set + se.insert({n+1, key}); // Insert the new pair with updated count + } + + // Decrement the count of the key + void dec(string key) { + int n = count[key]; // Get current count + count[key]--; // Decrement the count + se.erase({n, key}); // Remove the old pair from set + if (count[key] > 0) se.insert({n-1, key}); // If count > 0, insert updated pair + else count.erase(key); // If count reaches 0, remove the key from map + } + + // Get the key with the maximum count + string getMaxKey() { + if (!se.empty()) return se.rbegin()->second; // Last element gives the maximum + return ""; + } + + // Get the key with the minimum count + string getMinKey() { + if (!se.empty()) return se.begin()->second; // First element gives the minimum + return ""; + } +}; + +/** + * Your AllOne object will be instantiated and called as such: + * AllOne* obj = new AllOne(); + * obj->inc(key); + * obj->dec(key); + * string param_3 = obj->getMaxKey(); + * string param_4 = obj->getMinKey(); + */