Chunk Array - Problem
Given an array arr and a positive integer size, your task is to divide the array into smaller subarrays (chunks) where each chunk contains exactly size elements.
Think of it like organizing items into boxes: if you have 10 items and want to put 3 items per box, you'd get 3 boxes with 3 items each, and 1 box with the remaining 1 item.
Key Points:
- Each chunk should have exactly
sizeelements - The last chunk may have fewer elements if the array length isn't evenly divisible by
size - Maintain the original order of elements
- Return an array of subarrays (chunks)
Example: [1, 2, 3, 4, 5] with size 2 becomes [[1, 2], [3, 4], [5]]
Input & Output
example_1.py โ Basic chunking
$
Input:
arr = [1, 2, 3, 4, 5], size = 2
โบ
Output:
[[1, 2], [3, 4], [5]]
๐ก Note:
The array is divided into chunks of size 2. First chunk gets [1,2], second chunk gets [3,4], and the last chunk gets the remaining element [5].
example_2.py โ Perfect division
$
Input:
arr = [1, 2, 3, 4, 5, 6], size = 3
โบ
Output:
[[1, 2, 3], [4, 5, 6]]
๐ก Note:
The array length (6) is perfectly divisible by chunk size (3), resulting in two complete chunks of equal size.
example_3.py โ Single element chunks
$
Input:
arr = [1, 2, 3], size = 1
โบ
Output:
[[1], [2], [3]]
๐ก Note:
Each element becomes its own chunk when size is 1. This creates individual arrays for each element.
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Start with an empty box and conveyor belt of items
2
Fill Box
Take items from belt and place them in current box until full
3
New Box
When box is full, seal it and start packing a new box
4
Final Box
When items run out, seal the partially filled box
Key Takeaway
๐ฏ Key Insight: Sequential processing mirrors real-world packing - we don't need to pre-calculate positions, just fill boxes naturally as items arrive!
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, each element is processed exactly once
โ Linear Growth
Space Complexity
O(n)
Space needed for the result array containing all elements
โก Linearithmic Space
Constraints
- 1 โค size โค 1000
- 0 โค arr.length โค 1000
- -1000 โค arr[i] โค 1000
- Do not use lodash's _.chunk function
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code