Named list elements in R Programming - Time & Space Complexity
When working with named list elements in R, it is important to understand how accessing these elements affects performance.
We want to know how the time to find an element changes as the list grows.
Analyze the time complexity of the following code snippet.
my_list <- list(a = 1, b = 2, c = 3, d = 4, e = 5)
value <- my_list[["c"]]
This code creates a named list and accesses an element by its name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Searching through the list names to find the matching name.
- How many times: In the worst case, it checks each name once until it finds the match.
As the list grows, the time to find a named element grows roughly in proportion to the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of checks grows linearly with the list size.
Time Complexity: O(n)
This means the time to find a named element grows directly with the number of elements in the list.
[X] Wrong: "Accessing a named element is always instant, no matter the list size."
[OK] Correct: R searches the names one by one, so bigger lists take longer to find the element.
Understanding how named element access scales helps you write efficient R code and explain performance in interviews confidently.
What if we changed the list to a named vector instead? How would the time complexity of accessing an element by name change?