Assignment operators in R Programming - Time & Space 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.
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 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.
Each time n grows, the number of assignments grows 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, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to complete the assignments grows in a straight line as the input size increases.
[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.
Knowing how assignment operations scale helps you explain how your code handles larger data, a key skill in programming and interviews.
"What if we replaced the loop with a vectorized sum function? How would the time complexity change?"