0
0
Rustprogramming~5 mins

Assignment operators in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Assignment operators
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time n grows, the loop runs more times, doing one assignment each time.

Input Size (n)Approx. Operations
1010 assignments
100100 assignments
10001000 assignments

Pattern observation: The work grows directly with n; double n means double the assignments.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete the assignments grows in a straight line with the input size.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we replaced the loop with a recursive function doing the same += assignment? How would the time complexity change?"