0
0
Pythonprogramming~5 mins

Extending parent behavior in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Extending parent behavior
O(n)
Understanding Time Complexity

When we extend parent behavior in programming, we often add new actions on top of existing ones.

We want to see how this affects the time it takes for the program to run as the input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Parent:
    def process(self, data):
        for item in data:
            print(item)

class Child(Parent):
    def process(self, data):
        super().process(data)
        for item in data:
            print(item * 2)

This code shows a child class extending a parent's method by first running the parent's loop, then adding its own loop over the same data.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Two separate loops over the input list.
  • How many times: Each loop runs once over all items in the input.
How Execution Grows With Input

As the input list gets bigger, the program runs two loops, each touching every item once.

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, but still in a straight line.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly in proportion to the size of the input list.

Common Mistake

[X] Wrong: "Because there are two loops, the time complexity is squared, like O(n²)."

[OK] Correct: The loops run one after another, not inside each other, so their times add up, not multiply.

Interview Connect

Understanding how extending behavior affects time helps you explain your code clearly and shows you can think about efficiency in real projects.

Self-Check

"What if the child class added a nested loop inside its process method? How would the time complexity change?"