Nested lists in R Programming - Time & Space Complexity
When working with nested lists in R, it is important to understand how the time to process them grows as the size of the lists increases.
We want to know how the number of steps changes when we look inside each list within another list.
Analyze the time complexity of the following code snippet.
nested_list <- list(
list(1, 2, 3),
list(4, 5),
list(6, 7, 8, 9)
)
for (sublist in nested_list) {
for (item in sublist) {
print(item)
}
}
This code goes through each sublist inside a main list and prints every item inside those sublists.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner loop that goes through each item in every sublist.
- How many times: It runs once for each item inside all sublists combined.
As the total number of items inside all sublists grows, the number of print operations grows at the same rate.
| Input Size (total items) | Approx. Operations |
|---|---|
| 10 | About 10 prints |
| 100 | About 100 prints |
| 1000 | About 1000 prints |
Pattern observation: The work grows directly with the total number of items inside all nested lists combined.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the total number of items inside all the nested lists.
[X] Wrong: "Because there are two loops, the time complexity must be O(n²)."
[OK] Correct: The loops are nested over different levels, but the total number of items processed is just the sum of all items, not their product. So the time grows linearly, not quadratically.
Understanding how nested lists affect time helps you explain how your code handles complex data. This skill shows you can think clearly about how your program grows with input size.
"What if the nested lists were replaced by a single flat list? How would the time complexity change?"