0
0
Rustprogramming~5 mins

Output using println macro in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Output using println macro
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

Each additional line means one more print operation, so the total work grows steadily with n.

Input Size (n)Approx. Operations
1010 print calls
100100 print calls
10001000 print calls

Pattern observation: The total time grows directly in proportion to the number of lines printed.

Final Time Complexity

Time Complexity: O(n)

This means the time to print grows in a straight line as you print more lines.

Common Mistake

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

Interview Connect

Understanding how output operations scale helps you reason about program speed and efficiency in real tasks.

Self-Check

"What if we replaced println! with a function that prints two lines per iteration? How would the time complexity change?"