Junior — Middle
How is fast key lookup with approximately O(1) access time implemented in a dictionary data structure?
sobes.tech AI
Answer from AI
Fast key lookup with access time around O(1) in a dictionary data structure is implemented using a hash table. The main idea is to compute the hash value of the key, which serves as an index for accessing the element in the array.
Working principle:
- The key is transformed into a hash code using a hash function.
- The hash code is used to determine the position in the array (bucket).
- If there are multiple elements in the bucket (collision), a collision resolution method (such as chaining or open addressing) is used.
In Swift, the Dictionary is implemented based on a hash table, which provides amortized access time of O(1).
Example of using a dictionary in Swift:
var dict: [String: Int] = ["apple": 3, "banana": 5]
if let value = dict["apple"] {
print("Value: \(value)") // Outputs: Value: 3
}