design-hashset.dart (1342B)
1 //Design your own hashset where you can add, remove, and 2 //check to see if a value is contained in the map all in constant* time. 3 //The time compexity of add, remove, contains are 4 //ideally constant, but there are many cases in which the 5 //efficency divulves into near O(n) search time. As an example 6 //if all values have the same hashed value then they all need 7 //to be traversed to find the value you are searching for. 8 9 //How does it work? Well when a key is added it is divided by 100 10 //and the remainder is what the hash value is. Given that every time 11 //the value is searched for the same hash appears this works albeit this solution 12 //is quite lazy because depending on the data set there may be lots of collisions. 13 //For removing you simply hash the value then find the key in the map and remove it. 14 //For contains you simply search the given hash index for the key. 15 16 //Time: 545ms Beats: 75% 17 //Memory: 177.3MB Beats: 75% 18 class MyHashSet { 19 List<List<int>> hash_set = List.filled(100 , []); 20 MyHashSet() { 21 } 22 23 void add(int key) { 24 if(contains(key)){ 25 return; 26 } 27 ((hash_set[key%100]).add(key)); 28 } 29 30 void remove(int key) { 31 (hash_set[key%100]).remove(key); 32 } 33 34 bool contains(int key) { 35 if((hash_set[key%100]).contains(key)){ 36 return true; 37 } 38 return false; 39 } 40 } 41