Scalar data types in Rust - Time & Space Complexity
Let's see how the time it takes to work with scalar data types changes as we use more values.
We want to know how the program's steps grow when handling these simple data pieces.
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 using scalar integers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to total inside a loop.
- How many times: Once for every number in the input list.
As the list gets longer, the program adds more numbers one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The steps grow directly with the number of items.
Time Complexity: O(n)
This means the time to add numbers grows in a straight line with how many numbers there are.
[X] Wrong: "Adding numbers is always instant, no matter how many there are."
[OK] Correct: Each number must be added one by one, so more numbers mean more steps.
Understanding how simple data operations grow helps you explain your code clearly and shows you know how programs handle data efficiently.
"What if we changed the input from a list to a fixed-size array? How would the time complexity change?"