Accessing elements (indexing, first, last) in Ruby - Time & Space Complexity
When we get elements from a list by position, like the first or last item, it's important to know how long it takes as the list grows.
We want to find out how the time to access elements changes when the list gets bigger.
Analyze the time complexity of the following code snippet.
arr = [10, 20, 30, 40, 50]
first_element = arr.first
last_element = arr.last
third_element = arr[2]
This code gets the first, last, and third elements from an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Direct access to elements by position (indexing)
- How many times: Each access happens once, no loops or repeated steps
Getting an element by its position takes the same short time no matter how big the list is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same even if the list grows larger.
Time Complexity: O(1)
This means accessing any element by position takes a constant, quick amount of time regardless of list size.
[X] Wrong: "Accessing the last element takes longer because it's at the end of the list."
[OK] Correct: In Ruby arrays, the last element is stored just like any other, so getting it is just as fast as the first or any indexed element.
Knowing that accessing elements by index is fast helps you explain how your code handles data efficiently, a useful skill in many coding conversations.
"What if we used a linked list instead of an array? How would accessing the last element's time complexity change?"