0
0
Pythonprogramming~5 mins

Polymorphism through inheritance in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Polymorphism through inheritance
O(n)
Understanding Time Complexity

Let's see how the time taken by a program changes when using polymorphism through inheritance.

We want to know how the program's steps grow as we use more objects with inherited behaviors.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        print("Woof")

class Cat(Animal):
    def speak(self):
        print("Meow")

animals = [Dog(), Cat(), Dog()]
for animal in animals:
    animal.speak()

This code creates a list of animals and calls their speak method, which behaves differently depending on the animal type.

Identify Repeating Operations
  • Primary operation: Looping through the list of animals and calling their speak method.
  • How many times: Once for each animal in the list.
How Execution Grows With Input

Each animal in the list causes one speak call, so the work grows as the list grows.

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

Pattern observation: The number of operations grows directly with the number of animals.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line as you add more animals to the list.

Common Mistake

[X] Wrong: "Polymorphism makes the program slower because it adds extra steps for each method call."

[OK] Correct: The extra steps are very small and do not change how the total time grows with more animals; the main factor is still how many animals you have.

Interview Connect

Understanding how polymorphism affects time helps you explain your code's behavior clearly and shows you know how programs scale with more data.

Self-Check

"What if we added a nested loop inside each speak method? How would the time complexity change?"