0
0
R Programmingprogramming~5 mins

Vector indexing (1-based) in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Vector indexing (1-based)
O(k)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

Getting one element takes about the same time no matter the vector size.

Input Size (n)Approx. Operations
101 for single element, 3 for three elements
1001 for single element, 3 for three elements
10001 for single element, 3 for three elements

Pattern observation: Time grows with how many elements you ask for, not the total vector size.

Final Time Complexity

Time Complexity: O(k)

This means the time depends on how many elements you access, not the whole vector size.

Common Mistake

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

Interview Connect

Knowing how vector access time works helps you write faster code and explain your choices clearly.

Self-Check

"What if we accessed elements using a loop instead of all at once? How would the time complexity change?"