String values and text handling in Python - Time & Space Complexity
When working with text in programming, it is important to know how the time to process strings grows as the text gets longer.
We want to understand how the time needed changes when handling bigger pieces of text.
Analyze the time complexity of the following code snippet.
def count_vowels(text):
vowels = 'aeiouAEIOU'
count = 0
for char in text:
if char in vowels:
count += 1
return count
This code counts how many vowels are in a given string by checking each character one by one.
- Primary operation: Looping through each character in the string.
- How many times: Once for every character in the input text.
As the string gets longer, the code checks more characters, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows directly with the length of the string.
Time Complexity: O(n)
This means the time to count vowels grows in a straight line as the string gets longer.
[X] Wrong: "Checking if a character is a vowel takes constant time, so the whole function is always super fast regardless of string size."
[OK] Correct: While each check is quick, the total time depends on how many characters there are, so longer strings take more time overall.
Understanding how string length affects processing time helps you explain your code clearly and shows you think about efficiency in real tasks.
"What if we changed the code to count vowels only in the first half of the string? How would the time complexity change?"