0
0
Rubyprogramming~5 mins

Pure functions concept in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Pure functions concept
O(n)
Understanding Time Complexity

We want to understand how the time a pure function takes changes as the input size grows.

How does the work inside a pure function scale when given bigger inputs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def sum_array(arr)
  arr.reduce(0) { |total, num| total + num }
end

numbers = [1, 2, 3, 4, 5]
result = sum_array(numbers)

This code defines a pure function that adds all numbers in an array and returns the total.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding each number in the array one by one.
  • How many times: Once for each element in the array.
How Execution Grows With Input

As the array gets bigger, the function adds more numbers, so it takes more steps.

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

Pattern observation: The number of steps grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the input size grows.

Common Mistake

[X] Wrong: "Pure functions always run instantly no matter the input size."

[OK] Correct: Even pure functions do work on each input item, so bigger inputs take more time.

Interview Connect

Understanding how pure functions scale helps you write clear and predictable code that performs well as data grows.

Self-Check

"What if we changed the function to call itself recursively for each element? How would the time complexity change?"