Output using println macro in Rust - Time & Space Complexity
We want to understand how the time it takes to print output changes as we print more lines.
How does the number of print statements affect the total time?
Analyze the time complexity of the following code snippet.
fn main() {
let n = 10; // example value for n
for i in 0..n {
println!("Line number: {}", i);
}
}
This code prints a line for each number from 0 up to n - 1.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs and calls println! once per iteration.
- How many times: Exactly n times, where n is the input size.
Each additional line means one more print operation, so the total work grows steadily with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print calls |
| 100 | 100 print calls |
| 1000 | 1000 print calls |
Pattern observation: The total time grows directly in proportion to the number of lines printed.
Time Complexity: O(n)
This means the time to print grows in a straight line as you print more lines.
[X] Wrong: "Printing many lines takes the same time as printing just one line."
[OK] Correct: Each print call takes time, so more lines mean more total time.
Understanding how output operations scale helps you reason about program speed and efficiency in real tasks.
"What if we replaced println! with a function that prints two lines per iteration? How would the time complexity change?"