Loop execution flow in Rust - Time & Space Complexity
Loops run code multiple times, so their speed depends on how many times they repeat.
We want to know how the total work grows as the loop runs more times.
Analyze the time complexity of the following code snippet.
fn sum_numbers(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.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to total inside the for-loop.
- How many times: Once for every number in the list.
As the list gets longer, the loop runs more times, doing more additions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the list size.
[X] Wrong: "The loop runs a fixed number of times, so time is constant."
[OK] Correct: The loop runs once for each item, so if the list grows, the loop runs more times.
Understanding how loops affect time helps you explain code speed clearly and confidently.
"What if we added a nested loop inside the existing loop? How would the time complexity change?"