Formatting output in Rust - Time & Space Complexity
When we format output in Rust, we want to know how the time it takes changes as the data grows.
We ask: How does printing or formatting many items affect the program's speed?
Analyze the time complexity of the following code snippet.
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for num in &numbers {
println!("Number: {}", num);
}
}
This code prints each number in a list with some text formatting.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list and formatting it for printing.
- How many times: Once for each number in the list (n times).
As the list gets bigger, the program formats and prints more lines.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 formatting and print operations |
| 100 | About 100 formatting and print operations |
| 1000 | About 1000 formatting and print operations |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to format and print grows in a straight line with the number of items.
[X] Wrong: "Formatting output is always very fast and does not depend on how many items we print."
[OK] Correct: Each item needs its own formatting and printing step, so more items mean more work and more time.
Understanding how output formatting scales helps you write efficient programs and explain your code clearly in interviews.
"What if we changed the loop to format all numbers into one big string before printing? How would the time complexity change?"
Practice
{} do in Rust's println! macro?Solution
Step 1: Understand the role of
The{}in formatting{}acts as a placeholder where Rust inserts the value of a variable or expression inside a string.Step 2: Recognize its use in
When usingprintln!println!("Hello, {}", name);, Rust replaces{}with the value ofname.Final Answer:
It inserts the value of a variable or expression into the string. -> Option BQuick Check:
Placeholder{}= Insert value [OK]
- Thinking {} creates variables
- Assuming {} repeats strings
- Confusing {} with comments
Solution
Step 1: Identify correct decimal formatting syntax
Rust uses{:.2}insideprintln!to format a float with 2 decimal places.Step 2: Check each option
println!("{:.2}", 3.14159); uses{:.2}, which is correct. Others use invalid or incorrect syntax.Final Answer:
println!("{:.2}", 3.14159); -> Option AQuick Check:
Decimal places = {:.2} [OK]
- Using {2f} or {.2f} which is invalid in Rust
- Omitting the colon before precision
- Confusing with other language formats
let x = 255;
println!("Decimal: {}, Hex: {:x}, Binary: {:b}", x, x, x);Solution
Step 1: Understand formatting specifiers
{}prints decimal,{:x}prints lowercase hex,{:b}prints binary.Step 2: Convert 255 to hex and binary
255 decimal isffin hex (lowercase) and11111111in binary.Final Answer:
Decimal: 255, Hex: ff, Binary: 11111111 -> Option DQuick Check:
Hex lowercase = {:x}, Binary = {:b} [OK]
- Expecting uppercase hex without :X
- Adding 0x prefix automatically
- Miscounting binary digits
let num = 42;
println!("Number: {2}", num);Solution
Step 1: Check placeholder indexing
The placeholder{2}means use the third argument (index 2), but only one argumentnumis provided.Step 2: Understand argument count mismatch
Since only one argument exists, index 2 is out of range, causing a runtime error.Final Answer:
The placeholder {2} refers to an argument index that does not exist. -> Option CQuick Check:
Placeholder index must match argument count [OK]
- Using wrong index in placeholders
- Assuming Rust auto-corrects missing arguments
- Thinking semicolon needed inside string
let name = "Alice"; let score = 93; // Which println! line is correct?
Solution
Step 1: Understand alignment specifiers
{:<10}aligns left in 10 spaces,{:>5}aligns right in 5 spaces.Step 2: Match alignment to requirements
Names should be left aligned, scores right aligned, so println!("{:<10} | {:>5}", name, score); matches perfectly.Final Answer:
println!("{:<10} | {:>5}", name, score); -> Option AQuick Check:
Left align = <, Right align = > [OK]
- Swapping alignment symbols
- Omitting width numbers
- Using center alignment when not needed
Ready to prove it?
Pass the test and this pattern moves unknown
