Ctrl K

Fold a Tape into a Grid

Easy
A warehouse exported its sensor readings as one long tape, the list items. For a report they need to be laid out as a table with rows rows and cols columns. Fill the table row by row: the first cols numbers of the tape make the first row, the next cols make the second, and so on. The order of the numbers stays the same. The table must be completely filled and use every number. If that is impossible (there are more or fewer numbers than rows · cols), return an empty list.
Example 1
items=[4, 8, 15, 16, 23, 42], rows=3, cols=2 → [[4, 8], [15, 16], [23, 42]]

Six numbers exactly fill 3 rows of 2: [4, 8], [15, 16], [23, 42].

Example 2
items=[7, 7, 3], rows=1, cols=3 → [[7, 7, 3]]

A single row of three takes the whole list.

Example 3
items=[1, 2, 3, 4, 5], rows=2, cols=2 → []

A 2 × 2 grid holds 4 numbers but there are 5, so it cannot be done and the answer is empty.

Constraints
  • 1 ≤ len(items) ≤ 5 · 10⁴
  • 1 ≤ items[i] ≤ 10⁵
  • 1 ≤ rows, cols ≤ 4 · 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRepack the Tray EasyMirror and Negate a Bitmap EasySwap Rows and Columns EasyPawns the Rook Can Take EasyRolling Grid Easy
loading Python…
Input
items=[4, 8, 15, 16, 23, 42], rows=3, cols=2
Expected
[[4, 8], [15, 16], [23, 42]]

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.