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.
Example 1:
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:
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:
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:
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 array2 <= JSON.stringify(arr).length <= 1051 <= size <= arr.length + 1This 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.
The 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.
JavaScript
Java
C++
C
C#
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.
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.
The method keeps appending elements to the current chunk list until its length reaches size, at which point the chunk is added to the chunked result list. If there is a leftover partial chunk at the end, it is also added to the result.
JavaScript
Java
C++
C
C#
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.
| Approach | Complexity |
|---|---|
| Iterative Slicing | Time Complexity: O(n), where n is the number of elements in the array. |
| Using Modulo and Remainder Logic | Time Complexity: O(n), where n is the number of elements in the array. |
4 Leetcode Mistakes • Sahil & Sarra • 421,967 views views
Watch 9 more video solutions →Practice Chunk Array with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor