#1260
Easy Algorithms Shift 2d grid
Array Matrix Simulation
67.9% acceptance
Feb 25, 2026
1792
353
Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.
In one shift operation:
Element at grid[i][j] moves to grid[i][j + 1].
Element at grid[i][n - 1] moves to grid[i + 1][0].
Element at grid[m - 1][n - 1] moves to grid[0][0].
Return the 2D grid after applying shift operation k times.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn shift_grid(grid: Vec<Vec<i32>>, k: i32) -> Vec<Vec<i32>> {
let m = grid.len();
let n = grid[0].len();
let size = m * n;
let k = k as usize % size;
let flat: Vec<i32> = grid.into_iter().flatten().collect();
let mut result = vec![vec![0; n]; m];
for i in 0..size {
let new_pos = (i + k) % size;
result[new_pos / n][new_pos % n] = flat[i];
}
result
}
}