0
0
R Programmingprogramming~5 mins

Vector creation with c() in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Vector creation with c()
O(n)
Understanding Time Complexity

When we create a vector using the c() function in R, it is important to understand how the time to build that vector changes as we add more elements.

We want to know how the work grows when the vector gets longer.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


# Create a vector by combining elements
vec <- c(1, 2, 3, 4, 5)

# Add more elements
vec <- c(vec, 6, 7, 8)

# Print the vector
print(vec)
    

This code creates a vector by combining numbers using c(), then adds more elements by combining again.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Combining elements into a new vector using c()
  • How many times: Each time c() is called, it copies all existing elements plus new ones
How Execution Grows With Input

Each time we add elements with c(), R copies the entire vector to create a new one.

Input Size (n)Approx. Operations
10About 10 copy steps
100About 100 copy steps
1000About 1000 copy steps

Pattern observation: The work grows roughly in direct proportion to the number of elements copied.

Final Time Complexity

Time Complexity: O(n)

This means the time to create or extend a vector grows linearly with the number of elements.

Common Mistake

[X] Wrong: "Adding elements with c() is always very fast no matter how many elements there are."

[OK] Correct: Each time c() is used to add elements, it copies the whole vector, so the time grows with the vector size.

Interview Connect

Understanding how vector creation scales helps you write efficient R code and shows you can think about how programs handle data as it grows.

Self-Check

"What if we pre-allocate a vector of the final size and then fill it instead of using c() repeatedly? How would the time complexity change?"