0
0
R Programmingprogramming~5 mins

Assignment operators in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Assignment operators
O(n)
Understanding Time Complexity

Assignment operators are used to store values in variables. Understanding their time cost helps us see how fast our program runs when assigning values.

We want to know how the time to assign values changes as the amount of data grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


x <- 0
for (i in 1:n) {
  x <- x + i
}
print(x)

This code adds numbers from 1 to n, updating the variable x each time.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The assignment x <- x + i inside the loop.
  • How many times: This happens once for each number from 1 to n, so n times.
How Execution Grows With Input

Each time n grows, the number of assignments grows the same way.

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

Pattern observation: The number of assignments grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Assignment inside a loop is instant and does not affect time as n grows."

[OK] Correct: Each assignment takes time, and doing it many times adds up, so the total time grows with n.

Interview Connect

Knowing how assignment operations scale helps you explain how your code handles larger data, a key skill in programming and interviews.

Self-Check

"What if we replaced the loop with a vectorized sum function? How would the time complexity change?"