




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.
1import java.util.ArrayList;
2import java.util.List;
3
4public class ChunkArray {
5    public static List<List<Integer>> chunkArray(int[] arr, int size) {
6        List<List<Integer>> chunked = new ArrayList<>();
7        List<Integer> chunk = new ArrayList<>();
8        for (int n : arr) {
9            chunk.add(n);
10            if (chunk.size() == size) {
11                chunked.add(new ArrayList<>(chunk));
12                chunk.clear();
13            }
14        }
15        if (!chunk.isEmpty()) {
16            chunked.add(new ArrayList<>(chunk));
17        }
18        return chunked;
19    }
20}As elements are iterated over from arr, they are added to chunk. When chunk reaches the designated size, it is added to chunked and reset for new elements. Any elements remaining after completing array iteration form a final chunk.