Can anyone explain what is the complexity of the following Dictionary
methods?
ContainsKey(key) Add(key,value);
I'm trying to figure out the complexity of a method I wrote:
public void DistinctWords(String s) { Dictionary<string,string> d = new Dictionary<string,string>(); String[] splitted = s.split(" "); foreach ( String ss in splitted) { if (!d.containskey(ss)) d.add(ss,null); } }
I assumed that the 2 dictionary methods are of log(n) complexity where n is the number of keys in the dictionary. Is this correct?
If we explain the difference by Big O concepts, dictionaries have constant time complexity, O(1) while lists have linear time complexity, O(n).
The average time complexity is of course O(1). The best method would be to check and take a look at the hashs of the objects you are using. The CPython Dict uses int PyObject_Hash (PyObject *o) which is the equivalent of hash(o) .
If a dictionary/map is implemented as a HashMap , it has a best case complexity of O(1) , since i best case it requires exactly the calculation of the hash-code of the key element for retrieval, if there are no key collisions.
Time and space complexity of accessing an element in a dictionary. The time complexity to access an element in a dictionary is O(1) and the space complexity is also O(1), as we are not using any additional memory to access the element.
It's written in the documentation for Dictionary...
The Dictionary generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary class is implemented as a hash table.
And for the Add function:
If Count is less than the capacity, this method approaches an O(1) operation. If the capacity must be increased to accommodate the new element, this method becomes an O(n) operation, where n is Count.
Both methods have constant complexity:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With