Repack the Grid

EasyMatrix

Problem

A pallet of crates is described by an m × n grid. The warehouse wants to restack the same crates into a grid with rows rows and cols columns, keeping them in row-major order: read the original left to right, top to bottom, and fill the new grid in the same order.

Return the new grid. If rows · cols differs from m · n the restack is impossible: return the original grid unchanged.

Example 1

Input:
grid = [[1, 2], [3, 4]], rows = 1, cols = 4
Output:
[[1, 2, 3, 4]]

Reading order 1, 2, 3, 4 fills the single new row.

Example 2

Input:
grid = [[1, 2], [3, 4]], rows = 2, cols = 4
Output:
[[1, 2], [3, 4]]

8 cells cannot hold exactly 4 crates, so the grid is returned unchanged.

Example 3

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

Constraints

  • 1 ≤ m, n ≤ 100
  • 1 ≤ rows, cols ≤ 300
  • -1000 ≤ grid[i][j] ≤ 1000

Hint

Show the first hint

Picture both grids as the same flat list read in row-major order.

Walkthrough

How to approach it

01Clarify before coding

  • What if the sizes do not match? Return the original grid, unchanged.
  • Is the order row-major on both sides? Yes, read and write left to right, top to bottom.
  • Can rows · cols be larger than the input? Only as an impossible request, which falls under the first rule.

02Brute force

Flatten the grid into a list, then slice the list into rows of length cols.

Cost: O(m · n) time and an extra O(m · n) list. Perfectly fine; the direct index mapping simply avoids the temporary list.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.