We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Chunk Array

Difficulty: Easy


Problem Description

Given an array arr and a chunk size size, return a chunked array. A chunked array contains the original elements in arr, but consists of subarrays each of length size. The length of the last subarray may be less than size if arr.length is not evenly divisible by size. You may assume the array is the output of JSON.parse. In other words, it is valid JSON.


Key Insights

  • The problem requires partitioning an array into smaller subarrays of a specified size.
  • The last subarray can be smaller than the specified size if there are not enough elements left.
  • Handling edge cases such as an empty array or a chunk size larger than the array length is essential.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the input array. We traverse the array once to create the chunks. Space Complexity: O(n/k), where k is the chunk size, for the resulting array of chunks.


Solution

The solution involves iterating through the input array and creating subarrays of the specified size. We can use a loop to slice the array into chunks and store them in a new array. The algorithm maintains an index to track the current position in the input array and constructs the output by taking slices of the specified size.


Code Solutions

def chunk_array(arr, size):
    result = []
    for i in range(0, len(arr), size):
        result.append(arr[i:i + size])
    return result
← Back to All Questions