Map/collect for transformation in Ruby - Time & Space Complexity
We want to understand how long it takes to change each item in a list using map or collect.
How does the time grow when the list gets bigger?
Analyze the time complexity of the following code snippet.
numbers = [1, 2, 3, 4, 5]
squares = numbers.map do |num|
num * num
end
This code takes a list of numbers and creates a new list with each number squared.
- Primary operation: The map method loops through each item in the list.
- How many times: Once for each item in the list.
Each number in the list is processed one time to create the new list.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the list size.
[X] Wrong: "Map runs faster than looping because it's a special method."
[OK] Correct: Map still looks at every item one by one, so it takes about the same time as a simple loop.
Knowing how map works helps you explain how your code handles lists efficiently and clearly.
"What if we used map inside another map? How would the time complexity change?"