Junior — Middle
Which data structure provides faster access: array, set, or dictionary?
sobes.tech AI
Answer from AI
An array provides fast access by index — the operation of reading or writing an element by index is performed in O(1) time. However, searching for an element by value requires iteration (O(n)).
A Set and a Dictionary in Swift are implemented based on hash tables, which provide amortized access time to an element by key or presence check approximately O(1).
When it comes to index access — arrays are faster, but for access by key or value — sets and dictionaries provide faster access.
Example:
let array = ["a", "b", "c"]
let set: Set = ["a", "b", "c"]
let dict = ["key1": "a", "key2": "b"]
// Access by index in array
let element = array[1] // "b"
// Check for presence in set
let containsB = set.contains("b") // true
// Access by key in dictionary
let value = dict["key1"] // "a"