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

Number: 2798

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given an array arr and a chunk size, return a chunked array where the original elements are split into subarrays each of maximum length size. The last subarray may contain fewer than size elements if the total number of elements in arr is not evenly divisible by size.


Key Insights

  • The problem requires splitting an array into smaller subarrays (chunks) each of length equal to the given size.
  • When the number of elements is not a multiple of size, the last chunk will contain the remaining elements.
  • A simple iteration over the array using the step size can achieve the desired grouping efficiently.
  • The approach works in linear time by leveraging slicing or subarray creation.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(n), required for the output data structure holding all chunks.


Solution

The solution involves iterating over the original array in steps equal to the chunk size. For each iteration, a subarray (or chunk) is created from the current index to index + size and then added to the resulting list. This method ensures each element is processed exactly once, leading to an efficient and straightforward implementation.


Code Solutions

# Define a function to chunk an array with a given size.
def chunk_array(arr, size):
    # Initialize an empty list to store the chunks.
    chunks = []
    # Iterate through the array in steps of 'size'.
    for i in range(0, len(arr), size):
        # Slice the array from index i to i+size and add it to chunks.
        chunks.append(arr[i:i+size])
    # Return the final list of chunks.
    return chunks

# Example usage:
print(chunk_array([1,2,3,4,5], 1))   # Output: [[1], [2], [3], [4], [5]]
print(chunk_array([1,9,6,3,2], 3))     # Output: [[1, 9, 6], [3, 2]]
← Back to All Questions