Assignment operators in C++ - Time & Space Complexity
We want to see how the time taken by assignment operators changes as the input size changes.
How does the cost of assigning values grow when working with bigger data?
Analyze the time complexity of the following code snippet.
int arr[1000];
for (int i = 0; i < 1000; i++) {
arr[i] = i * 2;
}
int x = 5;
x = 10;
This code assigns values to each element of an array and then assigns a new value to a single variable.
- Primary operation: Assignment inside the loop to each array element.
- How many times: 1000 times, once for each element.
As the number of elements increases, 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 the input size.
Time Complexity: O(n)
This means the time to assign values grows in a straight line as the number of items increases.
[X] Wrong: "Assigning a single variable inside a loop makes the whole loop take constant time."
[OK] Correct: Even if the variable assignment is simple, doing it many times inside a loop adds up and grows with the number of repetitions.
Understanding how simple assignments add up helps you explain how loops affect performance in real code.
"What if we replaced the array with a linked list and assigned values similarly? How would the time complexity change?"