




Sponsored
Sponsored
This approach involves iterating over the array using a loop and extracting subarrays using slicing. The loop increments by the chunk size in each iteration, thus effectively slicing the array into chunks of the desired size.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n), storing the entire chunked array requires space proportional to the input size.
1
The chunkArray method iterates through the array with a step of size. Within each iteration, an inner loop collects elements into a subarray until either size elements are collected or the end of the array is reached.
This approach uses simple arithmetic operations to determine when to create a new subarray. Using the modulus operator allows checking if the number of currently collected elements is equal to the chunk size, upon which a new subarray is started.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n), because the additional space needed is proportional to the input size.
1#include <vector>
2
3std::vector<std::vector<int>> chunkArray(const std::vector<int>& arr, int size) {
4    std::vector<std::vector<int>> chunked;
5    std::vector<int> chunk;
6    for (int num : arr) {
7        chunk.push_back(num);
8        if (chunk.size() == size) {
9            chunked.push_back(chunk);
10            chunk.clear();
11        }
12    }
13    if (!chunk.empty()) {
14        chunked.push_back(chunk);
15    }
16    return chunked;
17}This implementation uses a vector to store individual chunks. Elements are collected in chunk until its size matches size, at which point it is added to chunked. Any elements in chunk at the end are also saved.