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?"
Practice
my_string[2] return when my_string = 'hello'?Solution
Step 1: Understand string indexing
Strings in Python start indexing at 0, so index 2 means the third character.Step 2: Identify the character at index 2
In 'hello', index 0='h', index 1='e', index 2='l'.Final Answer:
The third character 'l' -> Option CQuick Check:
Index 2 of 'hello' is 'l' [OK]
- Thinking indexing starts at 1
- Confusing index 2 with last character
- Assuming index 2 is out of range
text = 'abc'?Solution
Step 1: Understand how to loop over a string
Usingfor char in textiterates over each character directly.Step 2: Check each option
for i in range(text): print(i) tries to use range on a string (invalid). for char in text[1]: print(char) uses text[1] which is a single character, not iterable. for i in text.length: print(text[i]) uses text.length which is invalid in Python.Final Answer:
for char in text: print(char) -> Option AQuick Check:
Loop over string directly with for-in [OK]
- Using range() directly on string
- Using incorrect string length property
- Trying to loop over a single character
word = 'python'
result = ''
for i in range(len(word)):
if i % 2 == 0:
result += word[i]
print(result)Solution
Step 1: Understand the loop and condition
The loop runs from i=0 to i=5 (length 6). It adds characters at even indices (0,2,4).Step 2: Identify characters at even indices
word[0]='p', word[2]='t', word[4]='o'. Concatenate: 'pto'.Final Answer:
pto -> Option BQuick Check:
Even indices form 'pto' [OK]
- Including characters at odd indexes
- Confusing index counting starting at 1
- Adding characters incorrectly
text = 'data':for i in range(len(text)):
print(text(i))Solution
Step 1: Identify the indexing syntax error
In Python, to access a character by index, square brackets [] are used, not parentheses ().Step 2: Check the code line
The code usestext(i)which is a function call, causing a TypeError.Final Answer:
Using parentheses instead of square brackets for indexing -> Option AQuick Check:
Use text[i] to access characters, not text(i) [OK]
- Using parentheses instead of brackets
- Forgetting colon after for loop (not here)
- Misunderstanding len() usage
s = 'abracddabba', write code to create a new string containing only the characters at odd indices. What is the resulting string?Solution
Step 1: Identify odd indices in the string
Indices start at 0. Odd indices are 1,3,5,7,9.Step 2: Extract characters at odd indices
Characters: s[1]='b', s[3]='a', s[5]='d', s[7]='a', s[9]='b'. Concatenate: 'b'+'a'+'d'+'a'+'b' = 'badab'.Final Answer:
badab -> Option DQuick Check:
Characters at odd positions form 'badab' [OK]
- Including even indices
- Starting index count at 1 instead of 0
- Mixing up characters order
Ready to prove it?
Pass the test and this pattern moves unknown
