
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.
1using System;
2using System.Collections.Generic;
3
4public class ChunkArray {
5 public static List<List<int>> Chunk(int[] arr, int size) {
6 List<List<int>> chunked = new List<List<int>>();
7 List<int> chunk = new List<int>();
8 foreach (var num in arr) {
9 chunk.Add(num);
10 if (chunk.Count == size) {
11 chunked.Add(new List<int>(chunk));
12 chunk.Clear();
13 }
14 }
15 if (chunk.Count > 0) {
16 chunked.Add(new List<int>(chunk));
17 }
18 return chunked;
19 }
20}The method iterates through the array and appends elements to chunk until its size equals the specified size. Whenever chunk is full, it is copied to chunked and reset. Leftover elements form the last chunk.