Reading input basics in Rust - Time & Space Complexity
When reading input in Rust, it's important to know how the time to read grows as the input gets bigger.
We want to see how the program's work changes when the input size changes.
Analyze the time complexity of the following code snippet.
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
println!("You typed: {}", input.trim());
}
This code reads one line of input from the user and then prints it back.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading characters from input until a newline is found.
- How many times: Once per character in the input line.
As the input line gets longer, the program reads more characters one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character reads |
| 100 | About 100 character reads |
| 1000 | About 1000 character reads |
Pattern observation: The work grows directly with the number of characters typed.
Time Complexity: O(n)
This means the time to read input grows linearly with the input size.
[X] Wrong: "Reading input always takes the same time no matter how long it is."
[OK] Correct: The program reads each character one by one, so longer input means more work and more time.
Understanding how input reading scales helps you write programs that handle user data efficiently and avoid surprises with slow input handling.
"What if we read multiple lines in a loop instead of just one? How would the time complexity change?"
Practice
io::stdin().read_line(&mut input) in Rust?Solution
Step 1: Understand the function of
This function reads a line of input from the user and stores it in a mutable string.read_lineStep 2: Identify the purpose of
io::stdin()io::stdin()accesses the standard input stream, allowing the program to receive user input.Final Answer:
To read a line of text input from the user -> Option AQuick Check:
Reading input = B [OK]
- Confusing input reading with printing output
- Forgetting to make the string mutable
- Using read_line without a mutable reference
Solution
Step 1: Identify the need for mutability
To store user input, the string must be mutable becauseread_linemodifies it.Step 2: Check the correct syntax for mutable String
let mut input = String::new();correctly declares a mutable String variable.Final Answer:
let mut input = String::new(); -> Option CQuick Check:
Mutable String declaration = A [OK]
- Omitting 'mut' keyword for the input string
- Using &str instead of String for input storage
- Declaring input as immutable
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
println!("You typed: {}", input.trim());
}Solution
Step 1: Understand input reading and trimming
The program reads the input including the newline, buttrim()removes whitespace like newlines.Step 2: Analyze the output statement
The trimmed input "hello" is printed after "You typed: ".Final Answer:
You typed: hello -> Option BQuick Check:
Trim removes newline, output = D [OK]
- Not trimming input, so newline appears in output
- Expecting raw input without newline removal
- Confusing compile errors with runtime behavior
use std::io;
fn main() {
let input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
println!("Input: {}", input);
}Solution
Step 1: Check variable mutability
read_linerequires a mutable reference to modify the string, butinputis not mutable.Step 2: Confirm other parts are correct
Imports andprintln!syntax are correct; only mutability is missing.Final Answer:
The variable 'input' should be mutable -> Option AQuick Check:
Mutable variable needed for read_line = C [OK]
- Forgetting 'mut' keyword for input variable
- Thinking &mut is not needed for read_line
- Assuming println! syntax is wrong
i32 in Rust?Solution
Step 1: Read input into a mutable String
Input must be stored in a mutable String variable passed as a mutable reference toread_line.Step 2: Trim and parse input to i32
Usetrim()to remove whitespace, thenparse()to convert to integer, handling errors withexpect().Final Answer:
let mut age = String::new(); io::stdin().read_line(&mut age).expect("Failed"); let age: i32 = age.trim().parse().expect("Invalid number"); -> Option DQuick Check:
Mutable input + trim + parse = A [OK]
- Not making input string mutable
- Forgetting to trim before parsing
- Passing input without &mut to read_line
Ready to prove it?
Pass the test and this pattern moves unknown
