0
0
C++programming~5 mins

Assignment operators in C++ - Time & Space Complexity

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

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Assignment inside the loop to each array element.
  • How many times: 1000 times, once for each element.
How Execution Grows With Input

As the number of elements increases, the number of assignments grows in the same way.

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

Pattern observation: The number of assignments grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to assign values grows in a straight line as the number of items increases.

Common Mistake

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

Interview Connect

Understanding how simple assignments add up helps you explain how loops affect performance in real code.

Self-Check

"What if we replaced the array with a linked list and assigned values similarly? How would the time complexity change?"