Problem 385659 · easy · Level 03 Linear Management & Searching

Repacking the Seedling Trays

matrix · index arithmetic · list comprehension

A nursery's seedlings sit in an m x n tray, the grid matrix. They are moving to a tray with r rows and c columns (both positive): the seedlings are taken out in reading order (row by row, left to right) and set into the new tray in the same reading order. Return the new r x c grid. If the new tray has a different number of cells (r * c != m * n), the move is called off and you return the original matrix.

Examples

Input:  matrix = [[3, 8, 1, 6]], r = 2, c = 2
Output: [[3, 8], [1, 6]]

Input:  matrix = [[3, 8], [1, 6]], r = 3, c = 2
Output: [[3, 8], [1, 6]]
Explanation: 3 x 2 = 6 cells cannot hold exactly 4 elements, so the input is returned.

Constraints

  • Target: O(m * n) time.

Goals

  • Check that a reshape preserves the number of cells
  • Map a flat position to new coordinates with divmod
  • Return the original grid untouched when the reshape is impossible
Starting Python…