0
0
Rubyprogramming~5 mins

Accessing parent methods in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Accessing parent methods
O(n)
Understanding Time Complexity

When a child class calls a method from its parent class, it runs some code inherited from above. We want to see how the time it takes changes as the input grows.

How does calling a parent method affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Parent
  def process(items)
    items.each do |item|
      puts item * 2
    end
  end
end

class Child < Parent
  def process(items)
    super
  end
end

child = Child.new
child.process([1, 2, 3, 4, 5])

This code defines a parent class with a method that loops over a list and prints doubled values. The child class calls the parent's method using super.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping over each item in the list inside the parent method.
  • How many times: Once for each item in the input array.
How Execution Grows With Input

As the list gets bigger, the method runs the loop more times, doing more work.

Input Size (n)Approx. Operations
1010 times printing doubled values
100100 times printing doubled values
10001000 times printing doubled values

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 run grows in a straight line with the number of items in the list.

Common Mistake

[X] Wrong: "Calling super adds extra loops or doubles the work."

[OK] Correct: The child just calls the parent's method once. It does not repeat the loop multiple times, so the work stays proportional to the input size.

Interview Connect

Understanding how inherited methods run helps you explain code efficiency clearly. It shows you can think about how code layers affect performance, a useful skill in many coding tasks.

Self-Check

What if the child method added another loop over the items before calling super? How would the time complexity change?