0
0
R Programmingprogramming~5 mins

List creation in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: List creation
O(n)
Understanding Time Complexity

When we create a list in R, we want to know how the time to build it changes as the list gets bigger.

We ask: How does the work grow when we add more items to the list?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

my_list <- list()
for (i in 1:n) {
  my_list[[i]] <- i * 2
}

This code creates a list and fills it with numbers doubled from 1 to n.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding one item to the list inside the loop.
  • How many times: Exactly n times, once for each number from 1 to n.
How Execution Grows With Input

Each new item means one more step, so the work grows steadily as n grows.

Input Size (n)Approx. Operations
1010 steps
100100 steps
10001000 steps

Pattern observation: The time grows directly with the number of items added.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the list grows in a straight line as the list gets bigger.

Common Mistake

[X] Wrong: "Adding items to a list is instant and does not depend on size."

[OK] Correct: Each new item requires a step, so more items mean more time.

Interview Connect

Understanding how list creation time grows helps you explain efficiency clearly in interviews.

Self-Check

What if we pre-allocate the list size before the loop? How would the time complexity change?