Array slicing and ranges in Ruby - Time & Space Complexity
When we use array slicing and ranges in Ruby, we want to know how the time it takes grows as the array gets bigger.
We ask: How does the work change when we slice bigger parts of the array?
Analyze the time complexity of the following code snippet.
arr = (1..1000).to_a
slice = arr[100..199]
This code creates an array of 1000 numbers and then slices out 100 elements from it using a range.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Copying elements from the original array to the new slice.
- How many times: Once for each element in the slice range.
When the slice size grows, the work grows in the same way because each element is copied once.
| Input Size (slice length) | Approx. Operations |
|---|---|
| 10 | 10 copies |
| 100 | 100 copies |
| 1000 | 1000 copies |
Pattern observation: The number of operations grows directly with the slice size.
Time Complexity: O(k)
This means the time grows linearly with the number of elements you slice out.
[X] Wrong: "Slicing an array is always a constant time operation."
[OK] Correct: Because Ruby creates a new array and copies each element in the slice, so the time depends on how many elements you take.
Understanding how slicing works helps you explain efficiency when working with parts of arrays, a common task in coding challenges and real projects.
"What if we used a single index instead of a range for slicing? How would the time complexity change?"