Vector arithmetic (element-wise) in R Programming - Time & Space Complexity
When we do arithmetic on vectors in R, each element is processed one by one.
We want to know how the time to finish grows as the vector gets longer.
Analyze the time complexity of the following code snippet.
x <- 1:1000
y <- 1001:2000
z <- x + y # element-wise addition
This code adds two vectors element by element to create a new vector.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each pair of elements from two vectors.
- How many times: Once for each element in the vectors.
As the vector length grows, the number of additions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of elements.
Time Complexity: O(n)
This means the time to add vectors grows in a straight line with their length.
[X] Wrong: "Adding two vectors takes the same time no matter their size."
[OK] Correct: Each element must be added, so longer vectors take more time.
Understanding how vector operations scale helps you write efficient code and explain performance clearly.
"What if we added three vectors together element-wise instead of two? How would the time complexity change?"