NeetCode #964LC-2677EasyJavaScript
← Back to All Problems

#964 · #2677 · Chunk Array(分块数组)

📌 Problem Statement & Constraints

Given an array arr and a chunk size size, split the array into consecutive subarrays of length size, with the final chunk possibly shorter. Return the array of chunks.

💡 Core Algorithmic Approaches

  1. Iterate the indices with a step of size, taking slice(i, i + size) each time.
  2. slice handles a short trailing chunk automatically and never goes out of bounds.
  3. An empty input yields an empty result.
  4. The time is O(n) and the total copying done by slice is O(n).

💻 Benchmark Python3 Implementation

var chunk = function(arr, size) {
    const res = [];
    for (let i = 0; i < arr.length; i += size) {
        res.push(arr.slice(i, i + size));     // slice handles a short final chunk
    }
    return res;
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): every element is copied once.
💾 Space Complexity
O(n): the result array.

⚠️ Interview Pitfalls & Follow-ups

  • Stepping with i++: that degenerates into one chunk per element.
  • Using splice: it mutates the input, which is not allowed.
  • Returning [[]] for an empty array: the correct result is [].
  • Writing an inner push loop by hand: correct but longer; slice is clearer.