Description
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 togrid[i][j + 1]. - Element at
grid[i][n - 1]moves togrid[i + 1][0]. - Element at
grid[m - 1][n - 1]moves togrid[0][0].
Return the 2D grid after applying shift operation k times.
Example 1:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
Example 2:
Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
Example 3:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]
Constraints:
m == grid.lengthn == grid[i].length1 <= m <= 501 <= n <= 50-1000 <= grid[i][j] <= 10000 <= k <= 100
Solutions
This function flattens the 2D grid into a single 1D array, computes cut = k % arr.length to normalize the shift amount, then performs a circular right shift by slicing off the last cut elements and concatenating them to the front (arr.slice(-cut).concat(arr.slice(0, -cut))), and finally reshapes the shifted array back into the original m x n grid before returning it.
Language: javascript(2026-07-20 06:56)DONE
CPU Performance91.31%
Memory Performance30.12%
/**
* @param {number[][]} grid
* @param {number} k
* @return {number[][]}
*/
var shiftGrid = function(grid, k) {
const m = grid.length;
const n = grid[0].length;
let arr = [];
for (const row of grid) {
arr.push(...row);
}
const cut = k % arr.length;
arr = arr.slice(-cut).concat(arr.slice(0, -cut));
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
grid[i][j] = arr[n * i + j];
}
}
return grid;
};