Assignment operators in Rust - Time & Space Complexity
Assignment operators update values in variables. We want to see how the time to do this changes as the input grows.
How does the number of assignments affect the total work done?
Analyze the time complexity of the following code snippet.
let mut sum = 0;
for i in 1..=n {
sum += i; // assignment operator +=
}
println!("Sum: {}", sum);
This code adds numbers from 1 to n using the += assignment operator inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The += assignment inside the loop.
- How many times: Exactly n times, once for each number from 1 to n.
Each time n grows, the loop runs more times, doing one assignment each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The work grows directly with n; double n means double the assignments.
Time Complexity: O(n)
This means the time to complete the assignments grows in a straight line with the input size.
[X] Wrong: "Assignment operators like += are instant and don't add to time."
[OK] Correct: Each assignment inside a loop runs every time, so many assignments add up and affect total time.
Understanding how simple assignments inside loops add up helps you explain how code runs as input grows. This skill shows you can think about efficiency clearly.
"What if we replaced the loop with a recursive function doing the same += assignment? How would the time complexity change?"