String Traversal and Character Access in DSA Python - Time & Space Complexity
When we look at how fast a program runs that goes through a string, we want to know how the time changes as the string gets longer.
We ask: How does the time to check each letter grow when the string grows?
Analyze the time complexity of the following code snippet.
def print_chars(s):
for i in range(len(s)):
print(s[i])
This code goes through each character in the string and prints it one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing each character in the string one by one.
- How many times: Exactly once for each character in the string.
As the string gets longer, the number of times we print characters grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The operations grow directly with the string length; double the string, double the work.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the size of the string.
[X] Wrong: "Accessing each character is instant and does not add to time as the string grows."
[OK] Correct: Each character must be checked one by one, so more characters mean more time.
Understanding how going through a string works helps you explain how your code handles data step by step, a skill useful in many coding questions.
"What if we used a while loop with a pointer instead of a for loop? How would the time complexity change?"