Solving Leetcode Interviews in Seconds with AI: Reshape the Matrix
Introduction
In this blog post, we will explore how to solve the LeetCode problem "566" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix. The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. Example 1: Input: mat = [[1,2],[3,4]], r = 1, c = 4 Output: [[1,2,3,4]] Example 2: Input: mat = [[1,2],[3,4]], r = 2, c = 4 Output: [[1,2],[3,4]] Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 100 -1000 <= mat[i][j] <= 1000 1 <= r, c <= 300
Explanation
Here's the breakdown of the solution:
- Check Reshape Feasibility: First, verify if the reshape operation is possible by ensuring that the product of the original matrix dimensions (m n) equals the product of the desired dimensions (r c). If not, return the original matrix.
- Linear Traversal: If reshaping is possible, iterate through the original matrix in a row-major order.
Populate New Matrix: While traversing the original matrix, populate the new reshaped matrix, also in row-major order.
Runtime & Space Complexity: O(m n) - where m and n are the original dimensions. O(r c) for space, where r and c are the dimensions of the reshaped matrix if successful; otherwise O(1).
Code
def matrixReshape(mat, r, c):
m = len(mat)
n = len(mat[0])
if m * n != r * c:
return mat
reshaped_matrix = [[0] * c for _ in range(r)]
row_index = 0
col_index = 0
for i in range(m):
for j in range(n):
reshaped_matrix[row_index][col_index] = mat[i][j]
col_index += 1
if col_index == c:
col_index = 0
row_index += 1
return reshaped_matrix