0
0
Pythonprogramming~5 mins

Modifying object state in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Modifying object state
O(1)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

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
10About 1 operation per update
100Still about 1 operation per update
1000Still about 1 operation per update

Pattern observation: The time to update stays roughly the same no matter how many keys are stored.

Final Time Complexity

Time Complexity: O(1)

This means updating the object's state takes about the same time no matter how many keys it has.

Common Mistake

[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.

Interview Connect

Understanding how object state changes scale helps you explain efficiency clearly and confidently in real coding talks.

Self-Check

"What if the counts were stored in a list instead of a dictionary? How would the time complexity change?"