For loop in Rust - Time & Space Complexity
We want to understand how the time it takes to run a for loop changes as the amount of data grows.
Specifically, how does the number of steps increase when the loop runs over 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 the numbers in a list and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for loop that visits each number in the list.
- How many times: Once for every number in the input list.
As the list gets bigger, the loop runs more times, adding one step per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets longer.
[X] Wrong: "The loop runs a fixed number of times no matter the list size."
[OK] Correct: The loop actually runs once for each item, so bigger lists take more time.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave with more data.
"What if we replaced the for loop with two nested for loops over the same list? How would the time complexity change?"