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.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an m x n integer matrix grid, where m and n are both even integers, and an integer k.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:
Return the matrix after applying k cyclic rotations to it.
Example 1:
Input: grid = [[40,10],[30,20]], k = 1 Output: [[10,20],[40,30]] Explanation: The figures above represent the grid at every state.
Example 2:
Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2 Output: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]] Explanation: The figures above represent the grid at every state.
Constraints:
m == grid.lengthn == grid[i].length2 <= m, n <= 50m and n are even integers.1 <= grid[i][j] <= 50001 <= k <= 109Problem summary: You are given an m x n integer matrix grid, where m and n are both even integers, and an integer k. The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below: Return the matrix after applying k cyclic rotations to it.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[40,10],[30,20]] 1
[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] 2
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1914: Cyclically Rotating a Grid
class Solution {
private int m;
private int n;
private int[][] grid;
public int[][] rotateGrid(int[][] grid, int k) {
m = grid.length;
n = grid[0].length;
this.grid = grid;
for (int p = 0; p < Math.min(m, n) / 2; ++p) {
rotate(p, k);
}
return grid;
}
private void rotate(int p, int k) {
List<Integer> nums = new ArrayList<>();
for (int j = p; j < n - p - 1; ++j) {
nums.add(grid[p][j]);
}
for (int i = p; i < m - p - 1; ++i) {
nums.add(grid[i][n - p - 1]);
}
for (int j = n - p - 1; j > p; --j) {
nums.add(grid[m - p - 1][j]);
}
for (int i = m - p - 1; i > p; --i) {
nums.add(grid[i][p]);
}
int l = nums.size();
k %= l;
if (k == 0) {
return;
}
for (int j = p; j < n - p - 1; ++j) {
grid[p][j] = nums.get(k++ % l);
}
for (int i = p; i < m - p - 1; ++i) {
grid[i][n - p - 1] = nums.get(k++ % l);
}
for (int j = n - p - 1; j > p; --j) {
grid[m - p - 1][j] = nums.get(k++ % l);
}
for (int i = m - p - 1; i > p; --i) {
grid[i][p] = nums.get(k++ % l);
}
}
}
// Accepted solution for LeetCode #1914: Cyclically Rotating a Grid
func rotateGrid(grid [][]int, k int) [][]int {
m, n := len(grid), len(grid[0])
rotate := func(p, k int) {
nums := []int{}
for j := p; j < n-p-1; j++ {
nums = append(nums, grid[p][j])
}
for i := p; i < m-p-1; i++ {
nums = append(nums, grid[i][n-p-1])
}
for j := n - p - 1; j > p; j-- {
nums = append(nums, grid[m-p-1][j])
}
for i := m - p - 1; i > p; i-- {
nums = append(nums, grid[i][p])
}
l := len(nums)
k %= l
if k == 0 {
return
}
for j := p; j < n-p-1; j++ {
grid[p][j] = nums[k]
k = (k + 1) % l
}
for i := p; i < m-p-1; i++ {
grid[i][n-p-1] = nums[k]
k = (k + 1) % l
}
for j := n - p - 1; j > p; j-- {
grid[m-p-1][j] = nums[k]
k = (k + 1) % l
}
for i := m - p - 1; i > p; i-- {
grid[i][p] = nums[k]
k = (k + 1) % l
}
}
for i := 0; i < m/2 && i < n/2; i++ {
rotate(i, k)
}
return grid
}
# Accepted solution for LeetCode #1914: Cyclically Rotating a Grid
class Solution:
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
def rotate(p: int, k: int):
nums = []
for j in range(p, n - p - 1):
nums.append(grid[p][j])
for i in range(p, m - p - 1):
nums.append(grid[i][n - p - 1])
for j in range(n - p - 1, p, -1):
nums.append(grid[m - p - 1][j])
for i in range(m - p - 1, p, -1):
nums.append(grid[i][p])
k %= len(nums)
if k == 0:
return
nums = nums[k:] + nums[:k]
k = 0
for j in range(p, n - p - 1):
grid[p][j] = nums[k]
k += 1
for i in range(p, m - p - 1):
grid[i][n - p - 1] = nums[k]
k += 1
for j in range(n - p - 1, p, -1):
grid[m - p - 1][j] = nums[k]
k += 1
for i in range(m - p - 1, p, -1):
grid[i][p] = nums[k]
k += 1
m, n = len(grid), len(grid[0])
for p in range(min(m, n) >> 1):
rotate(p, k)
return grid
// Accepted solution for LeetCode #1914: Cyclically Rotating a Grid
/**
* [1914] Cyclically Rotating a Grid
*
* You are given an m x n integer matrix grid, where m and n are both even integers, and an integer k.
*
* The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
*
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/10/ringofgrid.png" style="width: 231px; height: 258px;" />
*
* A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/22/explanation_grid.jpg" style="width: 500px; height: 268px;" />
* Return the matrix after applying k cyclic rotations to it.
*
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/19/rod2.png" style="width: 421px; height: 191px;" />
*
* Input: grid = [[40,10],[30,20]], k = 1
* Output: [[10,20],[40,30]]
* Explanation: The figures above represent the grid at every state.
*
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/10/ringofgrid5.png" style="width: 231px; height: 262px;" /> <img alt="" src="https://assets.leetcode.com/uploads/2021/06/10/ringofgrid6.png" style="width: 231px; height: 262px;" /> <img alt="" src="https://assets.leetcode.com/uploads/2021/06/10/ringofgrid7.png" style="width: 231px; height: 262px;" />
*
*
* Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2
* Output: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]
* Explanation: The figures above represent the grid at every state.
*
*
*
* Constraints:
*
*
* m == grid.length
* n == grid[i].length
* 2 <= m, n <= 50
* Both m and n are even integers.
* 1 <= grid[i][j] <=^ 5000
* 1 <= k <= 10^9
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/cyclically-rotating-a-grid/
// discuss: https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn rotate_grid(grid: Vec<Vec<i32>>, k: i32) -> Vec<Vec<i32>> {
let k = k as usize;
let mut grid = grid;
let m = grid.len();
let n = grid[0].len();
let num_rings = m.min(n) / 2;
for i in 0..num_rings {
let num_rotations = k % (2 * (m + n - 4 * i) - 4);
for _ in 0..num_rotations {
for j in i..n - i - 1 {
grid[i].swap(j, j + 1);
}
for j in i..m - i - 1 {
let tmp = grid[j][n - i - 1];
grid[j][n - i - 1] = grid[j + 1][n - i - 1];
grid[j + 1][n - i - 1] = tmp;
}
let mut j = n - i - 1;
while j > i {
grid[m - i - 1].swap(j, j - 1);
j -= 1;
}
let mut j = m - i - 1;
while j > i + 1 {
let tmp = grid[j][i];
grid[j][i] = grid[j - 1][i];
grid[j - 1][i] = tmp;
j -= 1;
}
}
}
grid
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1914_example_1() {
let grid = vec![vec![40, 10], vec![30, 20]];
let k = 1;
let result = vec![vec![10, 20], vec![40, 30]];
assert_eq!(Solution::rotate_grid(grid, k), result);
}
#[test]
fn test_1914_example_2() {
let grid = vec![
vec![1, 2, 3, 4],
vec![5, 6, 7, 8],
vec![9, 10, 11, 12],
vec![13, 14, 15, 16],
];
let k = 2;
let result = vec![
vec![3, 4, 8, 12],
vec![2, 11, 10, 16],
vec![1, 7, 6, 15],
vec![5, 9, 13, 14],
];
assert_eq!(Solution::rotate_grid(grid, k), result);
}
}
// Accepted solution for LeetCode #1914: Cyclically Rotating a Grid
function rotateGrid(grid: number[][], k: number): number[][] {
const m = grid.length;
const n = grid[0].length;
const rotate = (p: number, k: number) => {
const nums: number[] = [];
for (let j = p; j < n - p - 1; ++j) {
nums.push(grid[p][j]);
}
for (let i = p; i < m - p - 1; ++i) {
nums.push(grid[i][n - p - 1]);
}
for (let j = n - p - 1; j > p; --j) {
nums.push(grid[m - p - 1][j]);
}
for (let i = m - p - 1; i > p; --i) {
nums.push(grid[i][p]);
}
const l = nums.length;
k %= l;
if (k === 0) {
return;
}
for (let j = p; j < n - p - 1; ++j) {
grid[p][j] = nums[k++ % l];
}
for (let i = p; i < m - p - 1; ++i) {
grid[i][n - p - 1] = nums[k++ % l];
}
for (let j = n - p - 1; j > p; --j) {
grid[m - p - 1][j] = nums[k++ % l];
}
for (let i = m - p - 1; i > p; --i) {
grid[i][p] = nums[k++ % l];
}
};
for (let p = 0; p < Math.min(m, n) >> 1; ++p) {
rotate(p, k);
}
return grid;
}
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.