0
0
Rubyprogramming~5 mins

Inherited hook in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Inherited hook
O(n)
Understanding Time Complexity

When Ruby classes inherit from each other, the inherited hook runs. We want to see how the time it takes to run this hook changes as more classes inherit.

How does the number of inherited classes affect the total work done by the hook?

Scenario Under Consideration

Analyze the time complexity of the following Ruby code using the inherited hook.

class Parent
  def self.inherited(subclass)
    puts "New subclass: #{subclass}"
  end
end

class Child1 < Parent; end
class Child2 < Parent; end
class Child3 < Parent; end

This code prints a message every time a new subclass inherits from Parent.

Identify Repeating Operations

Look at what repeats when new subclasses are created.

  • Primary operation: The inherited method runs once for each subclass.
  • How many times: Once per subclass created, so if there are n subclasses, it runs n times.
How Execution Grows With Input

As the number of subclasses grows, the total times the hook runs grows the same way.

Input Size (n subclasses)Approx. Operations (hook calls)
1010
100100
10001000

Pattern observation: The work grows directly with the number of subclasses.

Final Time Complexity

Time Complexity: O(n)

This means the total work done by the inherited hook grows in a straight line with the number of subclasses.

Common Mistake

[X] Wrong: "The inherited hook runs only once no matter how many subclasses there are."

[OK] Correct: The hook runs every time a new subclass is created, so it runs as many times as subclasses exist.

Interview Connect

Understanding how hooks like inherited scale helps you reason about code that runs automatically during class creation. This skill shows you can think about hidden costs in programs.

Self-Check

What if the inherited hook also created a new subclass inside itself? How would that affect the time complexity?