Array slice and splice in PHP - Time & Space Complexity
When working with arrays, slicing and splicing are common ways to get or change parts of the array.
We want to understand how the time it takes grows as the array gets bigger.
Analyze the time complexity of the following code snippet.
$array = range(1, 1000);
$slice = array_slice($array, 100, 200);
array_splice($array, 300, 100, [0, 0, 0]);
This code takes a part of the array without changing it, then removes and replaces a section inside the original array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Copying elements during slice and splice.
- How many times: For slice, it copies the requested part once. For splice, it removes and inserts elements, shifting others.
When the array size grows, the number of elements copied or shifted grows roughly with the size of the slice or splice.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Copy about 10 elements |
| 100 | Copy about 100 elements |
| 1000 | Copy about 100 elements for slice, and shifting elements for splice |
Pattern observation: The work grows roughly in direct proportion to the number of elements sliced or spliced.
Time Complexity: O(k + m)
This means the time depends on the size of the slice k and the number of elements affected by the splice m, not the whole array size.
[X] Wrong: "Slicing or splicing always takes time proportional to the entire array size."
[OK] Correct: Actually, these operations only work on the parts involved, so the time depends on how many elements you slice or splice, not the whole array.
Understanding how array slice and splice scale helps you write efficient code and explain your choices clearly in interviews.
"What if we splice at the start of a very large array instead of the middle? How would the time complexity change?"