Junior — Middle
Which search method is considered more efficient: array traversal or key-based lookup in a dictionary?
sobes.tech AI
Answer from AI
Accessing an element by key in a dictionary is considered a more efficient search method compared to iterating through an array.
Reasons:
- Dictionary is implemented based on a hash table, which provides an average access time of O(1).
- Array iteration (linear search) requires checking each element, with a search time of O(n).
Example in Swift:
let array = [1, 2, 3, 4, 5]
let dictionary = [1: "one", 2: "two", 3: "three"]
// Searching in array
if array.contains(3) {
print("Found")
}
// Searching by key in dictionary
if let value = dictionary[3] {
print("Found: \(value)")
}
Thus, if you need to frequently search for elements by key, it is better to use a dictionary.