0
0
DSA Pythonprogramming~5 mins

String Traversal and Character Access in DSA Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String Traversal and Character Access
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

As the string gets longer, the number of times we print characters grows the same way.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The operations grow directly with the string length; double the string, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows in a straight line with the size of the string.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if we used a while loop with a pointer instead of a for loop? How would the time complexity change?"