String Traversal and Character Access in DSA Rust - Time & Space Complexity
We want to know how long it takes to look at each letter in a word or sentence.
How does the time grow when the string gets longer?
Analyze the time complexity of the following code snippet.
fn print_chars(s: &str) {
for c in s.chars() {
println!("{}", c);
}
}
This code goes through each character in a string and prints it one by one.
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.
As the string gets longer, the number of steps grows in a straight line with the number of characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: Doubling the string length doubles the work.
Time Complexity: O(n)
This means the time to finish grows directly with the string length.
[X] Wrong: "Accessing each character is instant and does not depend on string length."
[OK] Correct: Each character must be visited one by one, so time grows with string size.
Understanding how string length affects processing time helps you explain your code clearly and shows you know how to handle data efficiently.
"What if we used indexing to access characters instead of iterating? How would the time complexity change?"
Practice
let s = "hello";
for c in s.chars() {
print!("{}-", c);
}Solution
Step 1: Understand the chars() method
Thechars()method returns an iterator over each character in the strings.Step 2: Trace the for loop printing
Each character is printed followed by a dash, so output ish-e-l-l-o-.Final Answer:
h-e-l-l-o- -> Option AQuick Check:
chars() + print with dash = h-e-l-l-o- [OK]
- Thinking chars() returns words
- Ignoring the dash printed after each char
- Confusing chars() with bytes()
s safely?Solution
Step 1: Understand string indexing in Rust
Rust strings cannot be indexed directly by integer due to UTF-8 encoding, sos[2]is invalid.Step 2: Use chars().nth() to get character safely
Thechars()iterator allows accessing the nth character safely withnth(2)andunwrap()to get the value.Final Answer:
let c = s.chars().nth(2).unwrap(); -> Option DQuick Check:
chars().nth(2).unwrap() = correct char access [OK]
- Using direct indexing like s[2]
- Using get(2) which returns Option<&str> slice, not char
- Using bytes() which returns u8, not char
let s = "rust";
let mut result = String::new();
for c in s.chars() {
if c == 'u' {
result.push('U');
} else {
result.push(c);
}
}
println!("{}", result);
Solution
Step 1: Iterate over each character in "rust"
The loop goes over 'r', 'u', 's', 't' one by one.Step 2: Replace 'u' with 'U' and keep others same
When character is 'u', push 'U' to result; else push original char.Final Answer:
rUst -> Option CQuick Check:
Only 'u' replaced by 'U' = rUst [OK]
- Replacing wrong characters
- Not pushing characters correctly
- Confusing uppercase and lowercase
let s = "hello";
let c = s[1];
println!("{}", c);
Solution
Step 1: Check string indexing rules in Rust
Rust strings are UTF-8 encoded and do not support direct indexing by integer like arrays.Step 2: Identify the invalid line
The linelet c = s[1];causes a compile-time error because of invalid indexing.Final Answer:
Cannot index string with integer directly -> Option BQuick Check:
Direct indexing on String = error [OK]
- Assuming s[1] works like array indexing
- Ignoring UTF-8 encoding complexity
- Thinking semicolon or macro syntax is the error
s, how can you create a new string containing only the vowels from s in Rust?Choose the correct code snippet.
Solution
Step 1: Use chars() to iterate characters
We need to check each character, sochars()is appropriate.Step 2: Filter vowels and collect into String
Filter characters that are vowels usingfilterand collect them into a new String.Final Answer:
let vowels: String = s.chars().filter(|c| "aeiou".contains(*c)).collect(); -> Option AQuick Check:
chars() + filter vowels + collect() = correct [OK]
- Using bytes() which returns u8, not char
- Using get() which slices string, not filters vowels
- Replacing non-vowels with spaces instead of filtering
Ready to prove it?
Pass the test and this pattern moves unknown
