String Traversal and Character Access in DSA C++ - Time & Space Complexity
We want to understand how long it takes to look at each letter in a word or sentence.
How does the time grow when the word gets longer?
Analyze the time complexity of the following code snippet.
#include <iostream>
#include <string>
void printChars(const std::string &s) {
for (size_t i = 0; i < s.length(); ++i) {
std::cout << s[i] << ' ';
}
std::cout << std::endl;
}
This code goes through each character in a string and prints it one by one.
- 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 steps grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 character accesses |
| 100 | 100 character accesses |
| 1000 | 1000 character accesses |
Pattern observation: The steps increase directly with the number of characters.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the string length.
[X] Wrong: "Accessing characters inside a string is instant and does not depend on string length."
[OK] Correct: Even though each access is quick, you must do it for every character, so total time grows with string size.
Knowing how string traversal time grows helps you explain and write efficient code when working with text data.
"What if we used a while loop with an iterator instead of indexing? How would the time complexity change?"
Practice
str[i] do when str is a string in C++?Solution
Step 1: Understand string indexing in C++
In C++, strings are like arrays of characters. Usingstr[i]accesses the character at positioni.Step 2: Clarify what
The expression returns the character stored at indexstr[i]returnsiwithout modifying the string.Final Answer:
Accesses the character at index i in the string -> Option BQuick Check:
str[i] = character at i [OK]
- Thinking it returns string length
- Assuming it deletes characters
- Confusing with string case conversion
str in C++?Solution
Step 1: Understand string length and indexing
String indices start at 0 and go up tostr.length() - 1. So loop must run whilei < str.length().Step 2: Check loop conditions
for (int i = 0; i < str.length(); i++) usesi < str.length()starting from 0, which correctly covers all characters without going out of bounds.Final Answer:
for (int i = 0; i < str.length(); i++) -> Option CQuick Check:
Loop from 0 to length-1 [OK]
- Using <= causes out-of-bounds error
- Starting loop at 1 misses first character
- Confusing length with last index
std::string s = "hello";
for (int i = 0; i < s.length(); i++) {
if (s[i] == 'l') {
std::cout << i << " ";
}
}Solution
Step 1: Identify characters and their indices
The string "hello" has characters: h(0), e(1), l(2), l(3), o(4).Step 2: Check which indices have 'l'
Characters at indices 2 and 3 are 'l', so those indices are printed.Final Answer:
2 3 -> Option DQuick Check:
Indices of 'l' = 2 3 [OK]
- Confusing character positions
- Printing characters instead of indices
- Off-by-one errors in indexing
str:for (int i = 0; i <= str.length(); i++) {
std::cout << str[i];
}Solution
Step 1: Analyze loop condition
The loop runs whilei <= str.length(), which means it tries to accessstr[str.length()].Step 2: Understand string indexing limits
Valid indices are from 0 tostr.length() - 1. Accessingstr[str.length()]is out-of-bounds and causes undefined behavior.Final Answer:
Using <= causes out-of-bounds access -> Option AQuick Check:
Loop must use <, not <= [OK]
- Using <= instead of < in loop condition
- Assuming string length is last index
- Ignoring out-of-bounds errors
str, how can you create a new string containing only the vowels from str using traversal and character access in C++?Solution
Step 1: Traverse the string character by character
Use a loop to access each character instrusing indexing.Step 2: Check if character is a vowel and build new string
If the character is one of 'a', 'e', 'i', 'o', 'u' (case-insensitive), append it to a new string variable.Step 3: Return or print the new string
After the loop, the new string contains only vowels from the original string.Final Answer:
Loop through str, check if each character is a vowel, and append it to a new string -> Option AQuick Check:
Filter vowels by checking each character [OK]
- Trying to extract vowels without looping
- Using substr incorrectly
- Sorting string changes order
Ready to prove it?
Pass the test and this pattern moves unknown
