Iterating over collections in Rust - Time & Space Complexity
When we go through items in a collection one by one, it takes time. We want to know how this time grows as the collection gets bigger.
The question is: How does the work change when the list has more items?
Analyze the time complexity of the following code snippet.
fn sum_elements(numbers: &[i32]) -> i32 {
let mut total = 0;
for &num in numbers {
total += num;
}
total
}
This code adds up all numbers in a list and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every item in the list.
As the list gets bigger, the time to add all numbers grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: Doubling the list size doubles the work needed.
Time Complexity: O(n)
This means the time grows directly with the number of items in the list.
[X] Wrong: "Looping over a list always takes the same time no matter how big it is."
[OK] Correct: The bigger the list, the more items to check, so it takes more time.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs handle data efficiently.
"What if we used two nested loops to compare every item with every other item? How would the time complexity change?"
Practice
let numbers = [1, 2, 3];
for num in numbers {
println!("{}", num);
}Solution
Step 1: Understand the for loop over an array
The for loop visits each element in the array named 'numbers'.Step 2: Action inside the loop
Each element is printed on its own line using println! macro.Final Answer:
Prints each number in the array on a new line -> Option BQuick Check:
for loop over array prints elements one by one [OK]
- Thinking arrays can't be iterated
- Expecting the whole array printed at once
- Confusing print! with println!
v in Rust?Solution
Step 1: Recall Rust for loop syntax
Rust uses 'for variable in collection' to iterate over items.Step 2: Check each option
for i in v { println!("{}", i); } matches correct syntax; others use invalid keywords.Final Answer:
for i in v { println!("{}", i); } -> Option AQuick Check:
Rust uses 'for ... in ...' loops [OK]
- Using 'to' instead of 'in'
- Using 'foreach' which is not Rust syntax
- Using 'loop' incorrectly
let v = vec![10, 20, 30];
let mut sum = 0;
for &num in &v {
sum += num;
}
println!("{}", sum);Solution
Step 1: Understand iteration with references
The loop uses '&num in &v' to borrow each element by reference and dereference it with '&num'.Step 2: Calculate sum of elements
sum starts at 0, then adds 10, 20, and 30, resulting in 60.Final Answer:
60 -> Option AQuick Check:
Sum of 10+20+30 = 60 [OK]
- Confusing references and values
- Expecting concatenation instead of sum
- Thinking borrowing causes error here
let arr = [1, 2, 3];
for num in arr {
num += 1;
println!("{}", num);
}Solution
Step 1: Check mutability of loop variable
In Rust, loop variables are immutable by default; 'num' is a copy of array element.Step 2: Understand why 'num += 1' fails
Trying to change 'num' causes error because it is not declared mutable.Final Answer:
Cannot modify 'num' because it is an immutable copy -> Option DQuick Check:
Loop variables are immutable unless declared mutable [OK]
- Thinking semicolon missing causes error
- Believing arrays can't be iterated
- Assuming loop vars are references by default
let words = vec!["apple", "banana", "cherry"];. How do you create a new vector containing the lengths of each word using iteration?Solution
Step 1: Use iterator and map to transform elements
words.iter() creates an iterator over references to strings; map applies a function to each element.Step 2: Collect results into a new vector
collect() gathers the mapped lengths into a Vec<usize>.Final Answer:
let lengths: Vec<usize> = words.iter().map(|w| w.len()).collect(); -> Option CQuick Check:
Use iter().map(...).collect() to transform collections [OK]
- Trying to use for loop as expression
- Using map directly on vector without iter()
- Using for_each which returns () not a collection
Ready to prove it?
Pass the test and this pattern moves unknown
