Skip to content
This repository has been archived by the owner on Oct 4, 2024. It is now read-only.

ALL_in_One_datastructure #206

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions ALL_in_One_datastructure.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
class AllOne {
public:
unordered_map<string,int> count; // Stores the count of each key
set<pair<int,string>> 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();
*/