Can anyone explain what is the complexity of
Dictionary.ContainsValue
?
I know that Dictionary.ContainsKey
complexity is O(1).
Can anyone explain what is the complexity of
Dictionary.ContainsValue
?
I know that Dictionary.ContainsKey
complexity is O(1).
Short answer : O(N)
Long Answer :
This method performs a linear search; therefore, the average execution time is proportional to Count. That is, this method is an O(n) operation, where n is Count.
O(n).
This method performs a linear search; therefore, the average execution time is proportional to Count. That is, this method is an O(n) operation, where n is Count.
Particularly, in Dictionary structure the key is generated in a hashing mechanism. When calling to ContainsKey
function it computes the hash code argument and checks if this computed argument exists in the hash table.
The value of the dictionary is not hashed and when calling to ContainsValue
function the algorithm has to iterate over the values stored until it finds the first matched item (if exists).
Note, if you use this function you might need another structure that will work with a better complexity. You might store all values in a HashSet<T>
.