JavaScriptEasyArrays10 min

Split an array into chunks

Split an integer array into consecutive chunks of size k; the final chunk may be shorter. All input is valid JSON satisfying the constraints; do not mutate the meaning of values through type coercion. Interviewers use this problem to assess advance through the array by the chunk size.

Input

A JSON object {"array": [...], "k": integer}.

Output

Print one compact JSON value: an array of arrays.

Constraints

0 <= array length <= 10000; 1 <= k <= 10000; integer elements between -1000000 and 1000000.

Example

Input

{"array":[1,2,3,4,5],"k":2}

Output

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

Example 2 input

{"array":[1,2,3],"k":10}

Output

[[1,2,3]]

Boundary case: A chunk size larger than the array produces one chunk

Public test cases (2)

  • Input

    {"array":[1,2,3,4,5],"k":2}

    Expected output

    [[1,2],[3,4],[5]]
  • Input

    {"array":[1,2],"k":1}

    Expected output

    [[1],[2]]
Hints (2)
  1. Slice at offsets that are multiples of k
  2. A chunk size larger than the array produces one chunk

Target complexity: time O(n) · space O(n)

Your solution

Checking runner availability…

Reference solution

Sign in for solution
All JavaScript programs