LeetCode Problem Workspace

Chunk Array

Chunk Array splits a given array into smaller subarrays of specified size, preserving original element order and handling uneven final chunks.

category

0

Topics

code_blocks

2

Code langs

hub

0

Related

Practice Focus

Easy · Chunk Array core interview pattern

bolt

Answer-first summary

Chunk Array splits a given array into smaller subarrays of specified size, preserving original element order and handling uneven final chunks.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Chunk Array core interview pattern

Try AiBox Copilotarrow_forward

This problem requires dividing an array into multiple subarrays where each subarray has at most the given size. The solution should preserve the original order of elements and correctly handle cases where the last chunk is smaller than the specified size. Avoid using external libraries like lodash to solve this efficiently in plain code.

Problem Statement

You are given an array arr and an integer size. Create a new array consisting of subarrays where each subarray contains size elements from arr, maintaining their original order. The last subarray may contain fewer elements if arr.length is not divisible by size.

Do not use any external libraries or built-in chunking functions. Implement the logic to iterate over arr and construct the chunked subarrays manually, ensuring correctness when size exceeds arr.length or when arr length is not evenly divisible.

Examples

Example 1

Input: arr = [1,2,3,4,5], size = 1

Output: [[1],[2],[3],[4],[5]]

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]]

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]]

Size is greater than arr.length thus all elements are in the first subarray.

Constraints

  • arr is a string representing the array.
  • 2 <= arr.length <= 105
  • 1 <= size <= arr.length + 1

Solution Approach

Iterative Chunking

Loop through arr using a step of size, slicing arr from the current index to index + size, and push each slice into a result array. This approach directly follows the Chunk Array core interview pattern and ensures proper handling of the last smaller chunk.

While Loop with Shift

Repeatedly remove the first size elements from arr using a while loop until arr is empty, and append each removed chunk to the result array. This approach is intuitive but modifies the original array, highlighting a common failure mode if original data must be preserved.

Preallocate and Fill

Precompute the number of chunks based on arr.length and size, then iterate to fill each subarray by indexing arr. This reduces repeated slicing but requires careful index calculation to avoid off-by-one errors, a frequent mistake in Chunk Array solutions.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

Time complexity is O(n) since each element is processed once. Space complexity is O(n) for the resulting chunked array. Choice of slicing or shifting may affect constant factors but not asymptotic behavior.

What Interviewers Usually Probe

  • They may ask about handling the last chunk when arr.length is not divisible by size.
  • Watch for edge cases where size is greater than arr.length.
  • They may probe in-place modification vs. creating a new array for chunking.

Common Pitfalls or Variants

Common pitfalls

  • Failing to handle the last chunk correctly when it contains fewer elements than size.
  • Modifying the original array unintentionally when using shift-based approaches.
  • Incorrectly calculating slice indices leading to missing or repeated elements.

Follow-up variants

  • Chunking multidimensional arrays while preserving nested structure.
  • Dynamic chunk size where size changes based on runtime conditions.
  • Reversing the order of chunks after splitting for alternate interview constraints.

FAQ

What is the best way to split an array into chunks in JavaScript?

Use a for loop with slicing or a while loop with shift, ensuring you handle the last chunk when arr.length is not divisible by size.

How does Chunk Array handle size larger than the array?

If size exceeds arr.length, the result is a single subarray containing all elements, preserving their original order.

Can I use lodash's _.chunk function to solve this problem?

No, the problem explicitly requires implementing chunking manually without external libraries.

What is the time complexity of chunking an array?

The time complexity is O(n) because each element is processed exactly once to form subarrays.

What common errors occur with the Chunk Array pattern?

Common mistakes include incorrect slice indices, failing to handle the final smaller chunk, and unintentionally modifying the original array.

terminal

Solution

Solution 1

#### TypeScript

1
2
3
4
5
6
7
8
9
10
11
12
/**
 * @param {Array} arr
 * @param {number} size
 * @return {Array[]}
 */
var chunk = function (arr, size) {
    const ans = [];
    for (let i = 0, n = arr.length; i < n; i += size) {
        ans.push(arr.slice(i, i + size));
    }
    return ans;
};
Chunk Array Solution: Chunk Array core interview pattern | LeetCode #2677 Easy