Accessing and setting values in Ruby - Time & Space Complexity
When we access or set values in data structures, it is important to know how the time it takes changes as the data grows.
We want to find out how fast or slow these operations are when the amount of data increases.
Analyze the time complexity of the following code snippet.
hash = { a: 1, b: 2, c: 3 }
value = hash[:b] # Accessing a value
hash[:d] = 4 # Setting a new value
This code accesses a value by key and then sets a new key-value pair in a hash.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Direct access and setting of values in a hash by key.
- How many times: Each operation happens once, no loops or repeated traversals.
Accessing or setting a value in a hash takes about the same time no matter how many items are inside.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays roughly the same even as the data grows larger.
Time Complexity: O(1)
This means accessing or setting a value takes a constant amount of time, no matter how big the hash is.
[X] Wrong: "Accessing a value takes longer if the hash has more items."
[OK] Correct: Hashes use a system that lets them find keys quickly without checking every item, so time stays about the same.
Knowing that accessing and setting values in hashes is fast helps you explain why you choose certain data structures in real projects.
"What if we changed the hash to an array and accessed values by index? How would the time complexity change?"