Assignment operators in Java - Time & Space Complexity
Let's see how assignment operators affect the time it takes for a program to run.
We want to know how the number of steps changes when using assignments in code.
Analyze the time complexity of the following code snippet.
int sum = 0;
for (int i = 0; i < n; i++) {
sum += i; // assignment operator +=
}
System.out.println(sum);
This code adds numbers from 0 up to n-1 and stores the result using an assignment operator.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The assignment operation
sum += iinside the loop. - How many times: It runs once for each number from 0 to n-1, so n times.
As n grows, the number of assignments grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The number of assignments grows directly with n, doubling n doubles the work.
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 make the code run faster or slower in a way that changes the overall time complexity."
[OK] Correct: Assignment operators themselves are simple steps. The total time depends on how many times they run, not the operator type.
Understanding how simple operations like assignments scale helps you explain code efficiency clearly and confidently.
"What if we replaced the loop with nested loops using assignment operators? How would the time complexity change?"