Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the complexity of these Dictionary methods?

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?

like image 465
Dan Dinu Avatar asked Sep 23 '11 17:09

Dan Dinu


People also ask

What is the complexity of dictionary?

If we explain the difference by Big O concepts, dictionaries have constant time complexity, O(1) while lists have linear time complexity, O(n).

What is the time complexity of Dict in Python?

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) .

Why is time complexity for dictionary O 1 )?

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.

What's the time complexity of a dictionary access?

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.


2 Answers

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.

like image 161
Reddog Avatar answered Sep 17 '22 19:09

Reddog


Both methods have constant complexity:

  • ContainsKey(key) - O(1)
  • Add(key,value) - O(1)
like image 25
Darin Dimitrov Avatar answered Sep 19 '22 19:09

Darin Dimitrov