Problem

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.

Please solve it without using lodash’s _.chunk function.

Examples

Example 1

1
2
3
Input: arr = [1,2,3,4,5], size = 1
Output: [[1],[2],[3],[4],[5]]
Explanation: The arr has been split into subarrays each with 1 element.

Example 2

1
2
3
Input: arr = [1,9,6,3,2], size = 3
Output: [[1,9,6],[3,2]]
Explanation: The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray.

Example 3

1
2
3
Input: arr = [8,5,3,2,6], size = 6
Output: [[8,5,3,2,6]]
Explanation: Size is greater than arr.length thus all elements are in the first subarray.

Example 4

1
2
3
Input: arr = [], size = 1
Output: []
Explanation: There are no elements to be chunked so an empty array is returned.

Constraints

  • arr is a valid JSON array
  • 2 <= JSON.stringify(arr).length <= 10^5
  • 1 <= size <= arr.length + 1

Solution

Method 1 – Iterative Slicing

Intuition

The main idea is to repeatedly take size elements from the input array and group them into subarrays. This is a direct and efficient way to chunk an array.

Approach

  1. Initialize an empty result array ans.
  2. Iterate over the input array in steps of size.
  3. For each step, slice a subarray of length size (or less for the last chunk) and append it to ans.
  4. Return the result array.

Code

1
2
3
4
5
6
7
8
9
class Solution {
    chunk(arr, size) {
        const ans = [];
        for (let i = 0; i < arr.length; i += size) {
            ans.push(arr.slice(i, i + size));
        }
        return ans;
    }
}
1
2
3
4
5
6
7
8
9
class Solution {
    chunk(arr: any[], size: number): any[][] {
        const ans: any[][] = [];
        for (let i = 0; i < arr.length; i += size) {
            ans.push(arr.slice(i, i + size));
        }
        return ans;
    }
}

Complexity

  • ⏰ Time complexity: O(n), where n is the length of the array.
  • 🧺 Space complexity: O(n), for the output array.