- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 89 lines of C++ from the credited upstream file 432.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Node {2 int count;3 unordered_set<string> keys;4};5 6class AllOne {7 public:8 void inc(string key) {9 if (const auto it = keyToIterator.find(key); it == keyToIterator.end())10 addNewKey(key);11 else12 incrementExistingKey(it, key);13 }14 15 void dec(string key) {16 const auto it = keyToIterator.find(key);17 18 19 decrementExistingKey(it, key);20 }21 22 string getMaxKey() {23 return nodeList.empty() ? "" : *nodeList.back().keys.begin();24 }25 26 string getMinKey() {27 return nodeList.empty() ? "" : *nodeList.front().keys.begin();28 }29 30 private:31 list<Node> nodeList; 32 unordered_map<string, list<Node>::iterator> keyToIterator;33 34 35 void addNewKey(const string& key) {36 if (nodeList.empty() || nodeList.front().count > 1)37 nodeList.push_front({1, {key}});38 else 39 nodeList.front().keys.insert(key);40 keyToIterator[key] = nodeList.begin();41 }42 43 44 void incrementExistingKey(45 unordered_map<string, list<Node>::iterator>::iterator it,46 const string& key) {47 const auto listIt = it->second;48 49 auto nextIt = next(listIt);50 const int newCount = listIt->count + 1;51 if (nextIt == nodeList.end() || nextIt->count > newCount)52 nextIt = nodeList.insert(nextIt, {newCount, {key}});53 else 54 nextIt->keys.insert(key);55 56 keyToIterator[key] = nextIt;57 remove(listIt, key);58 }59 60 61 void decrementExistingKey(62 unordered_map<string, list<Node>::iterator>::iterator it,63 const string& key) {64 const auto listIt = it->second;65 if (listIt->count == 1) {66 keyToIterator.erase(it);67 remove(listIt, key);68 return;69 }70 71 auto prevIt = prev(listIt);72 const int newCount = listIt->count - 1;73 if (listIt == nodeList.begin() || prevIt->count < newCount)74 prevIt = nodeList.insert(listIt, {newCount, {key}});75 else 76 prevIt->keys.insert(key);77 78 keyToIterator[key] = prevIt;79 remove(listIt, key);80 }81 82 83 void remove(list<Node>::iterator it, const string& key) {84 it->keys.erase(key);85 if (it->keys.empty())86 nodeList.erase(it);87 }88};89