Chunk Array - 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 not use lodash's _.chunk function.

Input & Output

Example 1 — Basic Chunking
$ Input: arr = [1,2,3,4,5], size = 2
Output: [[1,2],[3,4],[5]]
💡 Note: Split array into chunks of size 2: first chunk [1,2], second chunk [3,4], last chunk [5] has only 1 element
Example 2 — Perfect Division
$ Input: arr = [1,2,3,4,5,6], size = 3
Output: [[1,2,3],[4,5,6]]
💡 Note: Array length 6 divides evenly by size 3, creating two complete chunks of 3 elements each
Example 3 — 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

Constraints

  • 1 ≤ arr.length ≤ 1000
  • 1 ≤ size ≤ arr.length
  • -1000 ≤ arr[i] ≤ 1000

Visualization

Tap to expand
Chunk Array - Array Slicing Approach INPUT Original Array (arr): 1 2 3 4 5 0 1 2 3 4 Chunk Size: size = 2 Input Values: arr = [1,2,3,4,5] size = 2 Length: 5 elements Chunks needed: 3 ALGORITHM STEPS 1 Initialize Create empty result array result = [] 2 Loop with Step Iterate i = 0, 2, 4... i += size (step by 2) 3 Slice Array Extract chunk from i arr.slice(i, i+size) 4 Push to Result Add chunk to result result.push(chunk) Slice Operations: i=0: slice(0,2) --> [1,2] i=2: slice(2,4) --> [3,4] FINAL RESULT Chunked Array: Chunk 1 [1, 2] Chunk 2 [3, 4] Chunk 3 (partial) [5] Output: [[1,2],[3,4],[5]] OK - 3 chunks created Verification: 5 elements / size 2 = 3 chunks (last=1) Key Insight: Array slicing provides O(1) access to create chunks. By iterating with step = size, we jump directly to each chunk start. The slice(i, i+size) method handles the last partial chunk automatically when i+size exceeds array length. Time: O(n), Space: O(n) TutorialsPoint - Chunk Array | Optimized - Array Slicing
Asked in
Google 25 Amazon 20 Microsoft 15
28.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen