Vector indexing (1-based) in R Programming - Time & Space Complexity
We want to understand how long it takes to get elements from a vector in R.
How does the time change when we ask for one or many elements?
Analyze the time complexity of the following code snippet.
# Create a vector of numbers
vec <- 1:1000
# Access a single element
x <- vec[500]
# Access multiple elements
y <- vec[c(10, 20, 30)]
This code gets elements from a vector by their position using 1-based indexing.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing elements by index in the vector.
- How many times: Once for each element requested (single or multiple).
Getting one element takes about the same time no matter the vector size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 for single element, 3 for three elements |
| 100 | 1 for single element, 3 for three elements |
| 1000 | 1 for single element, 3 for three elements |
Pattern observation: Time grows with how many elements you ask for, not the total vector size.
Time Complexity: O(k)
This means the time depends on how many elements you access, not the whole vector size.
[X] Wrong: "Accessing an element takes longer if the vector is bigger."
[OK] Correct: Vector indexing in R directly jumps to the element, so size does not slow it down.
Knowing how vector access time works helps you write faster code and explain your choices clearly.
"What if we accessed elements using a loop instead of all at once? How would the time complexity change?"