0
0
R Programmingprogramming~5 mins

Nested lists in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested lists
O(n)
Understanding Time 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.

Scenario Under Consideration

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

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

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
10About 10 prints
100About 100 prints
1000About 1000 prints

Pattern observation: The work grows directly with the total number of items inside all nested lists combined.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if the nested lists were replaced by a single flat list? How would the time complexity change?"