chunk

Medium · Array Manipulations · 2 test cases

Given an array and chunk size, divide the array into many subarrays where each subarray is of length size.

Examples

chunk([1, 2, 3, 4], 2) → [[1, 2], [3, 4]]
chunk([1, 2, 3, 4, 5], 2) → [[1, 2], [3, 4], [5]]

Starter code

function chunk(array, size) {

}

Complexity of the optimal solution

Time O(n), space O(n). This solution iterates through each element of the input array (size n) once and pushes it into a subarray. Since every element is processed and stored once, the time and space complexity are both linear.

Solve chunk in the browser