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
- Iterate the indices with a step of
size, takingslice(i, i + size)each time. slicehandles a short trailing chunk automatically and never goes out of bounds.- An empty input yields an empty result.
- The time is O(n) and the total copying done by
sliceis 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;
sliceis clearer.