I'm prepping for interviews, and some obvious interview questions such as counting frequency of characters in a string involve putting all of the characters into a Hashtable/Dictionary in order to get O(n) runtime for the algorithm. My question is, what is the performance hit by using ContainsKey
and TryGetValue
to check to see if a key has already been inserted into the Hashtable? Can I still have an O(n) algorithm for problems like these that use ContainsKey
or TryGetValue
?
This method optimizes Dictionary usage. It gets a value (at a key) from a Dictionary. And it eliminates unneeded lookups, making programs better.
a) This is not thread-safe, as the underlying Dictionary itself is not thread safe. If another thread is calling Add at the same time, undefined behavior can occur.
ContainsKey is a Dictionary method in C# and check whether a key exists in the Dictionary or not. Declare a Dictionary and add elements − var dict = new Dictionary<string, int>() { {"TV", 1}, {"Home Theatre", 2}, {"Amazon Alexa", 3}, {"Google Home", 5}, {"Laptop", 5}, {"Bluetooth Speaker", 6} };
The most it can say is that if TryGetValue returns false, and if the type argument in question is a reference type or a nullable value, then the result will be null.
Assuming a good hash without too many collisions, each of those are O(1) operations.
As for how those operations work... I suggest you read up on hash tables.
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