Skip to content

1260. Shift 2D Grid 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
    const int m = grid.size();
    const int n = grid[0].size();
    vector<vector<int>> ans(m, vector<int>(n));

    k %= m * n;

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        const int index = (i * n + j + k) % (m * n);
        const int x = index / n;
        const int y = index % n;
        ans[x][y] = grid[i][j];
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public List<List<Integer>> shiftGrid(int[][] grid, int k) {
    final int m = grid.length;
    final int n = grid[0].length;
    List<List<Integer>> ans = new ArrayList<>();
    int[][] arr = new int[m][n];

    k %= m * n;

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        final int index = (i * n + j + k) % (m * n);
        final int x = index / n;
        final int y = index % n;
        arr[x][y] = grid[i][j];
      }

    for (int[] row : arr)
      ans.add(Arrays.stream(row).boxed().collect(Collectors.toList()));

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def shiftGrid(self, grid: list[list[int]], k: int) -> list[list[int]]:
    m = len(grid)
    n = len(grid[0])
    ans = [[0] * n for _ in range(m)]

    k %= m * n

    for i in range(m):
      for j in range(n):
        index = (i * n + j + k) % (m * n)
        x = index // n
        y = index % n
        ans[x][y] = grid[i][j]

    return ans