Array chunk and pad in PHP - Time & Space Complexity
When working with arrays, functions like chunking and padding help organize data into parts or fill missing spots.
We want to know how the time needed grows as the array gets bigger.
Analyze the time complexity of the following code snippet.
$array = [1, 2, 3, 4, 5, 6, 7];
$chunkSize = 3;
$chunks = array_chunk($array, $chunkSize);
foreach ($chunks as &$chunk) {
if (count($chunk) < $chunkSize) {
$chunk = array_pad($chunk, $chunkSize, 0);
}
}
This code splits an array into smaller parts of size 3, then fills the last part with zeros if it is smaller than 3.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Splitting the array into chunks and then checking each chunk.
- How many times: The foreach loop runs once for each chunk, roughly n divided by chunk size.
As the array size grows, the number of chunks grows proportionally, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations (splitting and padding checks) |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: The operations increase roughly in direct proportion to the input size.
Time Complexity: O(n)
This means the time needed grows in a straight line as the array gets bigger.
[X] Wrong: "Chunking and padding take constant time no matter the array size."
[OK] Correct: Both operations must look at each element at least once, so time grows with array size.
Understanding how chunking and padding scale helps you handle data processing tasks efficiently in real projects and interviews.
"What if we changed the chunk size to 1? How would the time complexity change?"