Formatting structured data in Python - Time & Space Complexity
When we format structured data, like turning a list or dictionary into a string, the time it takes depends on how much data we have.
We want to know how the work grows as the data gets bigger.
Analyze the time complexity of the following code snippet.
def format_data(data):
result = ""
for key, value in data.items():
result += f"{key}: {value}\n"
return result
This code takes a dictionary and creates a string with each key and value on its own line.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each key-value pair in the dictionary.
- How many times: Once for every item in the dictionary.
As the number of items grows, the work grows in a similar way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loops and string additions |
| 100 | About 100 loops and string additions |
| 1000 | About 1000 loops and string additions |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n^2)
This means the time to format the data grows quadratically with the number of items due to string concatenation in a loop.
[X] Wrong: "Formatting data is always super fast and doesn't depend on size."
[OK] Correct: Actually, the more items you have, the more work the program must do to format each one, so time grows with size.
Understanding how formatting time grows helps you explain how programs handle bigger data smoothly and why efficiency matters.
"What if we used a list of tuples instead of a dictionary? How would the time complexity change?"