Show problems as
Classic problem #2022EasyArrayMatrixSimulation

Convert 1D Array Into 2D Array

Real-world version: Laying the Tiles Into a Rack
Tracked in this browser only
Read Convert 1D Array Into 2D Array on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A run of tiles is to be laid into a rack of rows shelves, each shelf holding cols slots. Fill the rack shelf by shelf from the top, and within each shelf from left to right, taking the tiles in the order they are given.

Return the filled rack. When the run of tiles does not fill the rack exactly, return an empty list.

Examples

Example 1

Input
tiles = [1, 2, 3, 4, 5, 6], rows = 2, cols = 3
Output
[[1, 2, 3], [4, 5, 6]]

Six tiles fill two shelves of three slots, taken in order along the top shelf and then the bottom one.

Example 2

Input
tiles = [1, 2, 3, 4, 5], rows = 2, cols = 2
Output
[]

Five tiles cannot fill a rack of four slots, whichever way they are laid, so nothing is returned.

Example 3

Input
tiles = [5, 4, 3, 2, 1], rows = 5, cols = 1
Output
[[5], [4], [3], [2], [1]]

Five shelves of a single slot take the tiles one at a time in the order given.

Constraints

  • 1 <= tiles.length <= 5 * 10^4
  • 1 <= tiles[i] <= 10^5
  • 1 <= rows <= 4 * 10^4
  • 1 <= cols <= 4 * 10^4

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def construct2_d_array(tiles: list[int], rows: int, cols: int) -> list[list[int]]:
Java
public int[][] construct2DArray(int[] tiles, int rows, int cols)