Handling input values in Rust - Time & Space Complexity
When handling input values in Rust, it's important to know how the program's work grows as the input size changes.
We want to see how the time to process inputs changes when we get more or fewer values.
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).unwrap();
let numbers: Vec = input
.trim()
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect();
}
This code reads a line of input, splits it into parts, converts each part to a number, and stores them in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Splitting the input string and parsing each piece into a number.
- How many times: Once for each value entered in the input line.
As the number of input values grows, the program does more work to split and convert each one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 splits and parses |
| 100 | About 100 splits and parses |
| 1000 | About 1000 splits and parses |
Pattern observation: The work grows directly with the number of input values.
Time Complexity: O(n)
This means the time to handle input grows in a straight line with the number of values entered.
[X] Wrong: "Reading input is always constant time no matter how many values."
[OK] Correct: The program must look at each input value to split and convert it, so more values mean more work.
Understanding how input size affects processing time helps you write efficient programs and explain your code clearly in interviews.
"What if we read multiple lines of input instead of one? How would the time complexity change?"
Practice
io::stdin().read_line(&mut input) do in a program?Solution
Step 1: Understand the function purpose
io::stdin().read_line(&mut input)reads user input from the keyboard as a string.Step 2: Recognize the role of
The input is stored in the mutable variableinputinputpassed by reference.Final Answer:
It reads a line of text from the user and stores it in the variableinput. -> Option CQuick Check:
read_line reads user input [OK]
- Thinking read_line writes output
- Confusing input reading with clearing buffer
- Assuming it converts types automatically
Solution
Step 1: Check correct usage of read_line
It requires a mutable String reference:read_line(&mut input).Step 2: Confirm trimming is done on the input string
Callinginput.trim()removes whitespace correctly.Final Answer:
let mut input = String::new(); io::stdin().read_line(&mut input).expect("Failed"); let input = input.trim(); -> Option BQuick Check:
read_line needs &mut String and trim() cleans input [OK]
- Forgetting &mut before input
- Calling trim() on read_line() result
- Not creating a mutable String first
42?
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed");
let num: i32 = input.trim().parse().expect("Not a number");
println!("Number plus 10 is {}", num + 10);
}Solution
Step 1: Read and parse input
The input string "42" is trimmed and parsed to integer 42 successfully.Step 2: Add 10 and print
42 + 10 equals 52, so the output prints "Number plus 10 is 52".Final Answer:
Number plus 10 is 52 -> Option AQuick Check:
42 + 10 = 52 [OK]
- Not trimming input before parse
- Parsing input as wrong type
- Ignoring parse errors
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed");
let num: i32 = input.parse().expect("Not a number");
println!("Number: {}", num);Solution
Step 1: Check read_line usage
read_line correctly uses &mut input and input is mutable.Step 2: Identify parse error cause
parse() is called on input without trimming, so newline remains causing parse failure.Final Answer:
parse() called without trimming input -> Option AQuick Check:
Always trim input before parse() [OK]
- Forgetting to trim input before parse
- Assuming read_line returns trimmed string
- Misusing &mut in read_line
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed");
let numbers: Vec<i32> = input.trim().split_whitespace()
.map(|x| x.parse().expect("Not a number"))
.collect();
println!("Numbers: {:?}", numbers);
}Solution
Step 1: Read input line and trim
Input is read as a string and trimmed to remove trailing whitespace.Step 2: Split and parse each number
split_whitespace() splits input by spaces, map parses each piece to i32, collect gathers into vector.Final Answer:
Correctly reads and parses space-separated numbers into a vector. -> Option DQuick Check:
split_whitespace + map(parse) + collect = vector [OK]
- Parsing before splitting input
- Using wrong iterator methods
- Assuming read_line reads multiple inputs separately
Ready to prove it?
Pass the test and this pattern moves unknown
