Problem Description
Given an array arr and a chunk size, return a chunked array where the original elements are split into subarrays each of maximum length size. The last subarray may contain fewer than size elements if the total number of elements in arr is not evenly divisible by size.
Key Insights
- The problem requires splitting an array into smaller subarrays (chunks) each of length equal to the given size.
- When the number of elements is not a multiple of size, the last chunk will contain the remaining elements.
- A simple iteration over the array using the step size can achieve the desired grouping efficiently.
- The approach works in linear time by leveraging slicing or subarray creation.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(n), required for the output data structure holding all chunks.
Solution
The solution involves iterating over the original array in steps equal to the chunk size. For each iteration, a subarray (or chunk) is created from the current index to index + size and then added to the resulting list. This method ensures each element is processed exactly once, leading to an efficient and straightforward implementation.