09 Sept 2026Go / Python / TypeScriptEasy

Shift 2D Grid

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.

complexity

O(rows * columns) time and output space.

solution files

  • Go shift-2d-grid/solution.go
  • Python shift-2d-grid/solution.py
  • TypeScript shift-2d-grid/solution.ts

Solution files

Goshift-2d-grid/solution.go
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
}
Pythonshift-2d-grid/solution.py
class Solution:
    def shiftGrid(self, grid: list[list[int]], k: int) -> list[list[int]]:
        rows, columns = len(grid), len(grid[class="syntax-number">0]); total = rows * columns; result = [[class="syntax-number">0] * columns for _ in range(rows)]
        for index in range(total):
            destination = (index + k) % total
            result[destination class=class="syntax-string">"syntax-comment">// columns][destination % columns] = grid[index // columns][index % columns]
        return result
TypeScriptshift-2d-grid/solution.ts
function shiftGrid(grid: number[][], k: number): number[][] {
  const rows = grid.length; const columns = grid[class="syntax-number">0].length; const total = rows * columns; const result = Array.from({ length: rows }, () => new Array<number>(columns));
  for (let index = class="syntax-number">0; index < total; index += class="syntax-number">1) { const destination = (index + k) % total; result[Math.floor(destination / columns)][destination % columns] = grid[Math.floor(index / columns)][index % columns]; }
  return result;
}