Junior — Middle
Can you give examples of data structures that provide quick access to an element in constant time?
sobes.tech AI
Answer from AI
Data structures that provide access to an element in constant time (O(1)) include:
- Hash tables (HashMap, HashSet) — access by key occurs in amortized constant time.
- Arrays (Array) — access by index is performed in constant time.
Example in Kotlin for HashMap:
val map = hashMapOf("key1" to "value1", "key2" to "value2")
val value = map["key1"] // access in O(1)
It is important to remember that in the worst case (for example, in case of collisions in the hash table), the time can worsen, but on average, access is considered constant.