Hash creation with symbols and strings in Ruby - Time & Space Complexity
We want to understand how long it takes to create a hash with symbols and strings as keys.
How does the time needed change when the hash gets bigger?
Analyze the time complexity of the following code snippet.
hash = {}
keys = [:a, :b, :c, :d, :e]
values = [1, 2, 3, 4, 5]
keys.each_with_index do |key, i|
hash[key] = values[i]
hash[key.to_s] = values[i] * 10
end
This code creates a hash and adds pairs with symbol keys and string keys.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over the keys array to add entries to the hash.
- How many times: Once for each key in the keys array.
Each key causes two insertions into the hash, so the work grows as the number of keys grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 insertions |
| 100 | 200 insertions |
| 1000 | 2000 insertions |
Pattern observation: The number of operations grows directly with the number of keys.
Time Complexity: O(n)
This means the time to create the hash grows in a straight line as you add more keys.
[X] Wrong: "Adding string keys is slower than symbol keys because strings are longer."
[OK] Correct: Both insertions happen once per key, so the time depends on the number of keys, not the key type length.
Understanding how hash creation time grows helps you write efficient code and explain your choices clearly.
"What if we changed the code to add only symbol keys? How would the time complexity change?"