0
0
Pythonprogramming~5 mins

Iterating over strings in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Iterating over strings
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10About 10 prints
100About 100 prints
1000About 1000 prints

Pattern observation: The work grows directly with the number of characters. Double the characters, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in a straight line with the length of the string.

Common Mistake

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

Interview Connect

Understanding how looping through strings scales helps you explain your code clearly and shows you know how programs handle data as it grows.

Self-Check

"What if we nested another loop inside to compare each character with every other character? How would the time complexity change?"