← Home

432. All O`one Data Structure

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
432

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 432. All Oone Data Structure`, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • https://leetcode.com/problems/all-oone-data-structure/discuss/91416/Java-AC-all-strict-O(1)-not-average-O(1)-easy-to-read

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are inc, dec, getMaxKey, getMinKey, changeKey.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//https://leetcode.com/problems/all-oone-data-structure/discuss/91416/Java-AC-all-strict-O(1)-not-average-O(1)-easy-to-read
02//Runtime: 96 ms, faster than 63.80% of C++ online submissions for All O`one Data Structure.
03//Memory Usage: 25.6 MB, less than 37.00% of C++ online submissions for All O`one Data Structure.
04class Bucket{
05public:
06    int count;
07    unordered_set<string> keys;
08    Bucket *prev, *next;
09    
10    Bucket(int c){
11        count = c;
12        prev = next = nullptr;
13    };
14};
15
16class AllOne {
17public:
18    unordered_map<string, int> key2count;
19    unordered_map<int, Bucket*> count2bucket;
20    
21    //a doubly-linked list
22    Bucket *head, *tail;
23    
24    /** Initialize your data structure here. */
25    AllOne() {
26        head = new Bucket(INT_MIN);
27        tail = new Bucket(INT_MAX);
28        head->next = tail;
29        tail->prev = head;
30    }
31    
32    /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
33    void inc(string key) {
34        if(key2count.find(key) == key2count.end()){
35            key2count[key] = 1;
36            if(count2bucket.find(1) == count2bucket.end()){
37                count2bucket[1] = new Bucket(1);
38                // if(head->next->count != 1){
39                    insertBucketAfter(count2bucket[1], head);
40                // }
41            }
42            count2bucket[1]->keys.insert(key);
43        }else{
44            changeKey(key, 1);
45        }
46        // cout << key << " -> " << key2count[key] << endl;
47    }
48    
49    /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
50    void dec(string key) {
51        if(key2count.find(key) != key2count.end()){
52            int count = key2count[key];
53            if(count == 1){
54                key2count.erase(key);
55                removeKeyFromBucket(count2bucket[count], key);
56            }else{
57                changeKey(key, -1);
58            }
59        }
60        // cout << key << " -> " << key2count[key] << endl;
61    }
62    
63    /** Returns one of the keys with maximal value. */
64    string getMaxKey() {
65        return tail->prev == head ? "" : *(tail->prev->keys.begin());
66    }
67    
68    /** Returns one of the keys with Minimal value. */
69    string getMinKey() {
70        return head->next == tail ? "" : *(head->next->keys.begin());
71    }
72    
73    void changeKey(string& key, int offset){
74        //offset is 1 or -1
75        int oldcount = key2count[key];
76        int newcount = oldcount+offset;
77        key2count[key] = newcount;
78        
79        Bucket* oldbucket = count2bucket[oldcount];
80        
81        if(count2bucket.find(newcount) == count2bucket.end()){
82            count2bucket[newcount] = new Bucket(newcount);
83            insertBucketAfter(count2bucket[newcount], (offset == 1) ? oldbucket : oldbucket->prev);
84        }
85        
86        count2bucket[newcount]->keys.insert(key);
87        removeKeyFromBucket(oldbucket, key);
88    }
89    
90    void removeKeyFromBucket(Bucket* bucket, string& key){
91        bucket->keys.erase(key);
92        if(bucket->keys.empty()){
93            removeBucketFromList(bucket);
94            count2bucket.erase(bucket->count);
95        }
96    };
97    
98    void removeBucketFromList(Bucket* bucket){
99        bucket->prev->next = bucket->next;
100        bucket->next->prev = bucket->prev;
101        // delete bucket; //why not?
102        bucket->next = nullptr; 
103        bucket->prev = nullptr;
104    }
105    
106    void insertBucketAfter(Bucket* newbucket, Bucket* prebucket){
107        newbucket->prev = prebucket;
108        newbucket->next = prebucket->next;
109        prebucket->next->prev = newbucket;
110        prebucket->next = newbucket;    
111    }
112};
113
114/**
115 * Your AllOne object will be instantiated and called as such:
116 * AllOne* obj = new AllOne();
117 * obj->inc(key);
118 * obj->dec(key);
119 * string param_3 = obj->getMaxKey();
120 * string param_4 = obj->getMinKey();
121 */

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.