Sobes.tech
Junior — Middle

What is the time complexity of adding a new element to a dictionary?

sobes.tech AI

Answer from AI

The time complexity of adding a new element to a dictionary (for example, Dictionary in Swift or NSMutableDictionary in Objective-C) is usually O(1) on average. This is because the dictionary is implemented based on a hash table, where hash calculation and insertion occur in constant time.

However, in the worst case, during collisions or the need to resize the internal array, the complexity can temporarily increase to O(n), where n is the number of elements.

Example in Swift:

var dict = [String: Int]()
dict["key"] = 42 // Insertion in O(1) on average
What is the time complexity of adding a new element… - sobes.tech