0
0
Rubyprogramming~5 mins

Map/collect for transformation in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Map/collect for transformation
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: The map method loops through each item in the list.
  • How many times: Once for each item in the list.
How Execution Grows With Input

Each number in the list is processed one time to create the new list.

Input Size (n)Approx. Operations
1010 operations
100100 operations
10001000 operations

Pattern observation: The work grows directly with the number of items. Double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the list size.

Common Mistake

[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.

Interview Connect

Knowing how map works helps you explain how your code handles lists efficiently and clearly.

Self-Check

"What if we used map inside another map? How would the time complexity change?"