
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.
1The chunk_array function uses list comprehension which iterates over the array with a step size of size. It slices arr from index i to i + size in each iteration, creating subarrays of the desired chunk size.
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 <stdio.h>
2#include <stdlib.h>
3
4int** chunkArray(int* arr, int arrSize, int size, int* returnSize) {
5 int numChunks = (arrSize + size - 1) / size;
6 int** chunks = (int**)malloc(numChunks * sizeof(int*));
7 *returnSize = numChunks;
8 int currentIndex = 0;
9 for (int i = 0; i < numChunks; i++) {
10 int chunkSize = (currentIndex + size <= arrSize) ? size : arrSize - currentIndex;
11 chunks[i] = (int*)malloc(chunkSize * sizeof(int));
12 for (int j = 0; j < chunkSize; j++) {
13 chunks[i][j] = arr[currentIndex++];
14 }
15 }
16 return chunks;
17}This C implementation calculates chunks by iterating through the input array. Memory is allocated for each chunk according to the conditionally calculated chunkSize. The structure tracks the total number of chunks with returnSize.