Iterating over strings in Python - Time & Space Complexity
When we go through each letter in a word or sentence, we want to know how the time it takes grows as the word gets longer.
We ask: How does the work change when the string has more characters?
Analyze the time complexity of the following code snippet.
text = "hello world"
for char in text:
print(char)
# This code prints each character in the string one by one.
This code goes through each letter in the string and prints it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the string.
- How many times: Once for every character in the string.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 prints |
| 100 | About 100 prints |
| 1000 | About 1000 prints |
Pattern observation: The work grows directly with the number of characters. Double the characters, double the work.
Time Complexity: O(n)
This means the time it takes grows in a straight line with the length of the string.
[X] Wrong: "Looping over a string is instant no matter how long it is."
[OK] Correct: Each character still needs to be looked at one by one, so longer strings take more time.
Understanding how looping through strings scales helps you explain your code clearly and shows you know how programs handle data as it grows.
"What if we nested another loop inside to compare each character with every other character? How would the time complexity change?"