Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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.lengthn == mat[i].length1 <= m, n <= 100-1000 <= mat[i][j] <= 10001 <= r, c <= 300Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[1,2],[3,4]] 1 4
[[1,2],[3,4]] 2 4
convert-1d-array-into-2d-array)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #566: Reshape the Matrix
class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
int m = mat.length, n = mat[0].length;
if (m * n != r * c) {
return mat;
}
int[][] ans = new int[r][c];
for (int i = 0; i < m * n; ++i) {
ans[i / c][i % c] = mat[i / n][i % n];
}
return ans;
}
}
// Accepted solution for LeetCode #566: Reshape the Matrix
func matrixReshape(mat [][]int, r int, c int) [][]int {
m, n := len(mat), len(mat[0])
if m*n != r*c {
return mat
}
ans := make([][]int, r)
for i := range ans {
ans[i] = make([]int, c)
}
for i := 0; i < m*n; i++ {
ans[i/c][i%c] = mat[i/n][i%n]
}
return ans
}
# Accepted solution for LeetCode #566: Reshape the Matrix
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
ans = [[0] * c for _ in range(r)]
for i in range(m * n):
ans[i // c][i % c] = mat[i // n][i % n]
return ans
// Accepted solution for LeetCode #566: Reshape the Matrix
impl Solution {
pub fn matrix_reshape(mat: Vec<Vec<i32>>, r: i32, c: i32) -> Vec<Vec<i32>> {
let r = r as usize;
let c = c as usize;
let m = mat.len();
let n = mat[0].len();
if m * n != r * c {
return mat;
}
let mut i = 0;
let mut j = 0;
(0..r)
.into_iter()
.map(|_| {
(0..c)
.into_iter()
.map(|_| {
let res = mat[i][j];
j += 1;
if j == n {
j = 0;
i += 1;
}
res
})
.collect()
})
.collect()
}
}
// Accepted solution for LeetCode #566: Reshape the Matrix
function matrixReshape(mat: number[][], r: number, c: number): number[][] {
let m = mat.length,
n = mat[0].length;
if (m * n != r * c) return mat;
let ans = Array.from({ length: r }, v => new Array(c).fill(0));
let k = 0;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
ans[Math.floor(k / c)][k % c] = mat[i][j];
++k;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.