
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;
using 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.
1def chunk_array(arr, size):
2 chunked = []
3 chunk = []
4 for i in arr:
5 chunk.append(i)
6 if len(chunk) == size:
7 chunked.append(chunk)
8 chunk = []
9 if chunk:
10 chunked.append(chunk)
11 return chunkedThe method keeps appending elements to the current chunk list until its length reaches size, at which point the chunk is added to the chunked result list. If there is a leftover partial chunk at the end, it is also added to the result.