Integer types in Rust - Time & Space Complexity
When working with integer types in Rust, it's helpful to know how operations on them affect program speed.
We want to see how the time to run code changes as the numbers get bigger or smaller.
Analyze the time complexity of the following code snippet.
fn sum_numbers(numbers: &[i32]) -> i32 {
let mut sum = 0;
for &num in numbers {
sum += num;
}
sum
}
This code adds up all the integers in a list and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each integer to the sum inside a loop.
- How many times: Once for every number in the list.
As the list gets longer, the number of additions grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: Doubling the list size doubles the work done.
Time Complexity: O(n)
This means the time to add numbers grows directly with how many numbers there are.
[X] Wrong: "Adding integers is always instant, so time doesn't grow with input size."
[OK] Correct: While each addition is fast, doing many additions one after another takes more time as the list grows.
Understanding how simple operations like adding integers scale helps you explain program speed clearly and confidently.
"What if we changed the list to a nested list of integers? How would the time complexity change?"