0
0
Rubyprogramming~5 mins

Class methods with self prefix in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Class methods with self prefix
O(n)
Understanding Time Complexity

We want to understand how long a class method with the self prefix takes to run as the input size grows.

How does the work inside such a method change when we give it bigger input?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Calculator
  def self.sum(numbers)
    total = 0
    numbers.each do |num|
      total += num
    end
    total
  end
end

This method adds up all numbers in an array and returns the total.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the array.
  • How many times: Once for every number in the input array.
How Execution Grows With Input

As the list of numbers gets bigger, the method does more additions, one for each number.

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

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 input size.

Common Mistake

[X] Wrong: "Class methods with self run instantly no matter the input size."

[OK] Correct: Even though it's a class method, if it loops through input, the time depends on how big the input is.

Interview Connect

Knowing how class methods scale with input size helps you explain your code clearly and shows you understand efficiency.

Self-Check

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