DDSA Solutions

1260. Shift 2D Grid

Problem Overview

A grid shift is just a circular rotate on the flattened row-major sequence.

Intuition

A grid shift is just a circular rotate on the flattened row-major sequence. Mapping (i, j) ↔ i*n+j lets you add k (mod m·n) and convert back to coordinates, so every cell moves in one arithmetic step without simulating k individual wraps.

Algorithm

  1. 1Let m = rows, n = cols, and reduce k %= m*n.
  2. 2Allocate a new m×n matrix.
  3. 3For each cell (i, j) with value grid[i][j], compute index = (i*n + j + k) % (m*n).
  4. 4Write the value into (index / n, index % n).
  5. 5Copy the matrix into List<IList<int>> and return it.

Example Walkthrough

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1

  1. 1.Flattened order is 1,2,3,4,5,6,7,8,9. After one shift: 9,1,2,3,4,5,6,7,8.
  2. 2.Cell 1 at (0,0) goes to index 1 → (0,1). Cell 9 at (2,2) goes to index 0 → (0,0).
  3. 3.Result grid is [[9,1,2],[3,4,5],[6,7,8]].

Output: [[9,1,2],[3,4,5],[6,7,8]]

Common Pitfalls

  • Always take k modulo m*n; large k without reduction wastes work and can overflow if you are not careful with intermediates.
  • Column count n is the stride: index / n is the row, index % n is the column.
  • Write into a new matrix — shifting in place is messy because destinations overwrite unread sources.
  • k = 0 must return an equivalent grid (modulo makes this natural).
1260.cs
C#
public class Solution
{
    // Approach: Treat the grid as a flattened 1D array of length m*n. For each
    // cell (i, j), move it k positions forward in row-major order with wrap-around:
    // newIndex = (i*n + j + k) % (m*n), then write into (newIndex/n, newIndex%n).
    // Complexity: O(m·n) time and O(m·n) space.
    public IList<IList<int>> ShiftGrid(int[][] grid, int k)
    {
        int m = grid.Length;
        int n = grid[0].Length;
        var ans = new List<IList<int>>();
        int[,] arr = new int[m, n];

        k %= m * n;

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

        for (int i = 0; i < m; i++)
        {
            var row = new List<int>();
            for (int j = 0; j < n; j++)
                row.Add(arr[i, j]);
            ans.Add(row);
        }

        return ans;
    }
}
Was this solution helpful?

Related Problems