Extending parent behavior in Python - Time & Space 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.
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 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.
As the input list gets bigger, the program runs two loops, each touching every item once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (2 loops x 10 items) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: The total work grows roughly twice as fast as the input size, but still in a straight line.
Time Complexity: O(n)
This means the time to run grows directly in proportion to the size of the input list.
[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.
Understanding how extending behavior affects time helps you explain your code clearly and shows you can think about efficiency in real projects.
"What if the child class added a nested loop inside its process method? How would the time complexity change?"