- 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
- 59 lines of C++ from the credited upstream file insert-delete-getrandom-o1-duplicates-allowed.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.
123 4class RandomizedCollection {5public:6 7 RandomizedCollection() : gen_(random_device()()) {8 9 }10 11 12 bool insert(int val) {13 bool has = used_.count(val);14 15 list_.emplace_back(val, used_[val].size());16 used_[val].emplace_back(list_.size() - 1);17 18 return !has; 19 }20 21 22 bool remove(int val) {23 if (!used_.count(val)) {24 return false;25 }26 27 used_[list_.back().first][list_.back().second] = used_[val].back();28 swap(list_[used_[val].back()], list_.back());29 30 used_[val].pop_back();31 if (used_[val].empty()) {32 used_.erase(val);33 }34 list_.pop_back();35 36 return true; 37 }38 39 40 int getRandom() {41 uniform_int_distribution<int> dist(0, list_.size() - 1);42 return list_[dist(gen_)].first;43 }44 45private:46 vector<pair<int, int>> list_;47 unordered_map<int, vector<int>> used_;48 default_random_engine gen_;49};50 51/**52 * Your RandomizedCollection object will be instantiated and called as such:53 * RandomizedCollection obj = new RandomizedCollection();54 * bool param_1 = obj.insert(val);55 * bool param_2 = obj.remove(val);56 * int param_3 = obj.getRandom();57 */58 59