Modifying object state in Python - Time & Space Complexity
When we change the state of an object, we want to know how long it takes as the object grows.
We ask: how does the time to update the object change with its size?
Analyze the time complexity of the following code snippet.
class Counter:
def __init__(self):
self.counts = {}
def add(self, key):
if key in self.counts:
self.counts[key] += 1
else:
self.counts[key] = 1
This code updates a dictionary inside an object by increasing the count for a given key.
- Primary operation: Checking if a key exists and updating the dictionary.
- How many times: Each call updates one key once; repeated calls happen outside this snippet.
Each update looks up a key and changes its value. The time depends on how fast the dictionary can find the key.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 operation per update |
| 100 | Still about 1 operation per update |
| 1000 | Still about 1 operation per update |
Pattern observation: The time to update stays roughly the same no matter how many keys are stored.
Time Complexity: O(1)
This means updating the object's state takes about the same time no matter how many keys it has.
[X] Wrong: "Updating the count takes longer as the dictionary grows because it has more keys."
[OK] Correct: Dictionaries use fast lookups that keep update time steady, so size does not slow down each update.
Understanding how object state changes scale helps you explain efficiency clearly and confidently in real coding talks.
"What if the counts were stored in a list instead of a dictionary? How would the time complexity change?"