




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.
1using System.Collections.Generic;
public class ChunkArray {
    public static List<List<int>> Chunk(int[] arr, int size) {
        List<List<int>> chunked = new List<List<int>>();
        for (int i = 0; i < arr.Length; i += size) {
            List<int> chunk = new List<int>();
            for (int j = i; j < i + size && j < arr.Length; j++) {
                chunk.Add(arr[j]);
            }
            chunked.Add(chunk);
        }
        return chunked;
    }
}The Chunk method iterates through the input array with a step of size. It collects elements into a list chunk until reaching the specified size or the end of the array, after which the chunk is added to the result list.
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.