Treat the grid as one row-major circular array and map each source flat index to its shifted destination index.
Complexity
O(rows * columns) time and output space.
Shift a rectangular grid right by k positions with row and grid wrapping.
Treat the grid as one row-major circular array and map each source flat index to its shifted destination index.
O(rows * columns) time and output space.
package main
func shiftGrid(grid [][]int, k int) [][]int {
rows, columns := len(grid), len(grid[0])
total := rows * columns
result := make([][]int, rows)
for row := range result {
result[row] = make([]int, columns)
}
for index := 0; index < total; index++ {
destination := (index + k) % total
result[destination/columns][destination%columns] = grid[index/columns][index%columns]
}
return result
}
class Solution:
def shiftGrid(self, grid: list[list[int]], k: int) -> list[list[int]]:
rows, columns = len(grid), len(grid[0]); total = rows * columns; result = [[0] * columns for _ in range(rows)]
for index in range(total):
destination = (index + k) % total
result[destination // columns][destination % columns] = grid[index // columns][index % columns]
return result
function shiftGrid(grid: number[][], k: number): number[][] {
const rows = grid.length; const columns = grid[0].length; const total = rows * columns; const result = Array.from({ length: rows }, () => new Array<number>(columns));
for (let index = 0; index < total; index += 1) { const destination = (index + k) % total; result[Math.floor(destination / columns)][destination % columns] = grid[Math.floor(index / columns)][index % columns]; }
return result;
}