0
0
Rubyprogramming~5 mins

Super keyword behavior in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Super keyword behavior
O(n)
Understanding Time Complexity

We want to understand how using the super keyword affects the time it takes for a program to run.

Specifically, how does calling a method from a parent class impact execution as input grows?

Scenario Under Consideration

Analyze the time complexity of the following Ruby code using super.

class Parent
  def process(items)
    items.map { |item| item * 2 }
  end
end

class Child < Parent
  def process(items)
    result = super
    result.select { |x| x > 10 }
  end
end

child = Child.new
child.process([1, 5, 10, 20])

This code doubles each item in a list using the parent method, then filters the doubled items in the child method.

Identify Repeating Operations

Look for loops or repeated actions in the code.

  • Primary operation: Two loops over the list: one in the parent process method (map), and one in the child method (select).
  • How many times: Each loop runs once over all items, so twice over the input list.
How Execution Grows With Input

Each item in the input list is processed twice, once for doubling and once for filtering.

Input Size (n)Approx. Operations
10About 20 operations (2 loops x 10 items)
100About 200 operations
1000About 2000 operations

Pattern observation: The total work grows roughly twice as fast as the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly in proportion to the number of items.

Common Mistake

[X] Wrong: "Using super makes the method twice as slow in a way that changes the overall time complexity."

[OK] Correct: Calling super just adds another loop over the data, so it still grows linearly with input size, not exponentially or worse.

Interview Connect

Understanding how method calls like super affect performance helps you explain your code clearly and reason about efficiency in real projects.

Self-Check

What if the parent method used nested loops instead of a single loop? How would the time complexity change?