0
0
Pythonprogramming~5 mins

String representation methods in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String representation methods
O(n)
Understanding Time Complexity

Let's explore how the time it takes to create string representations changes as the input grows.

We want to know how the work grows when we convert objects or data to strings.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"Person(name={self.name}, age={self.age})"

n = 10  # Example value for n
people = [Person(f"Name{i}", i) for i in range(n)]
for p in people:
    print(str(p))

This code creates a list of people and prints their string representations.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of people and calling str() on each.
  • How many times: Exactly n times, once for each person.
How Execution Grows With Input

As the number of people grows, the total work grows in a straight line.

Input Size (n)Approx. Operations
1010 string conversions
100100 string conversions
10001000 string conversions

Pattern observation: Doubling the number of people doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all string representations grows directly with the number of items.

Common Mistake

[X] Wrong: "Calling str() on each object is constant time overall because each call is fast."

[OK] Correct: Even if one call is fast, doing it n times adds up, so total time grows with n.

Interview Connect

Understanding how string conversions scale helps you explain performance when working with lists or collections in real projects.

Self-Check

"What if the __str__ method included a loop over a list inside each object? How would the time complexity change?"