↓Skip to main content
  1. LeetCode/

LeetCode 566: Reshape the Matrix

·2 mins· ·
LeetCode Easy Array Matrix Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-27

  • Submissions: Runtime Error ×3 → Wrong Answer → Runtime Error ×3 → Accepted ×2

Approach
#

Treat the matrix as one row-major sequence (Matrix Template 2): element k sits at (k // n, k % n) in the original and (k // c, k % c) in the result. When m × n != r × c, reshaping is impossible and the original is returned.

My Attempts
#

This took 9 submissions:

  • The first three had syntax errors; attempt 4 returned False when reshaping was impossible (the original matrix is expected), sliced every r elements and wrapped each slice in an extra list.
  • After returning the original, the row length became c // r, which is 0 when r > c (ValueError); then mat // r, dividing a list (TypeError). len(mat) // r, which equals c, finally passed.

Solution
#

class Solution:
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        m, n = len(mat), len(mat[0])
        if m * n != r * c:
            return mat
        res = [[0] * c for _ in range(r)]
        for k in range(m * n):
            res[k // c][k % c] = mat[k // n][k % n]
        return res

Complexity
#

Time O(mn), space O(mn) (output).

Mistakes to Avoid
#

  • When reshaping is impossible return the original matrix, not False.
  • Each row holds c elements, so slices have length c, not r.

Interview Explanation
#

Viewing the matrix as one row-major sequence, element k is at k // n, k % n originally and at k // c, k % c in the result; if the counts differ I return the original. Time O(mn).

Related

LeetCode 463: Island Perimeter
·2 mins
LeetCode Easy Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 463 note: each land cell contributes 4 edges, minus 2 for each land neighbor above or to the left
LeetCode 495: Teemo Attacking
·2 mins
LeetCode Easy Array Simulation
LeetCode 495 note: each attack contributes min(gap to the next attack, duration), and the last one contributes the full duration
LeetCode 561: Array Partition
·1 min
LeetCode Easy Array Greedy Sorting Counting-Sort
LeetCode 561 note: sort and pair neighbors; each pair’s minimum is the element at an even index, so sum those
LeetCode 575: Distribute Candies
·1 min
LeetCode Easy Array Hash-Table
LeetCode 575 note: at most n / 2 candies can be eaten and at most len(set) kinds exist; the answer is the smaller of the two
LeetCode 414: Third Maximum Number
·1 min
LeetCode Easy Array Sorting
LeetCode 414 note: track the three largest distinct values, skipping repeats, and return the maximum if fewer than three distinct values exist
LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop