List creation in R Programming - Time & Space 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?
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 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.
Each new item means one more step, so the work grows steadily as n grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The time grows directly with the number of items added.
Time Complexity: O(n)
This means the time to create the list grows in a straight line as the list gets bigger.
[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.
Understanding how list creation time grows helps you explain efficiency clearly in interviews.
What if we pre-allocate the list size before the loop? How would the time complexity change?