
Sponsored
Sponsored
Transform the 2D grid into a 1D list: The problem of shifting all elements in a 2D grid can be simplified by flattening the grid into a 1D array. This enables easier shifting and indexing.
Shift the 1D Array: Determine the actual number of shifts needed by computing k % (m * n) to avoid redundant full rotations. Then partition and concatenate the 1D array accordingly to achieve the desired shift.
Transform back to 2D Grid: Finally, map the shifted 1D list back to the original 2D grid layout.
Time Complexity: O(m * n) since we access each grid element once.
Space Complexity: O(m * n) needed for the result grid storage.
1var shiftGrid = function(grid, k) {
2 const m = grid.length, n = grid[0].length;
3 const total = m * n;
4 k = k % total;
5 const flatGrid = grid.flat();
6 const shiftedGrid = [...flatGrid.slice(-k), ...flatGrid.slice(0, -k)];
7 const result = [];
8 for (let row = 0; row < m; row++) {
9 result.push(shiftedGrid.slice(row * n, row * n + n));
10 }
11 return result;
12};JavaScript uses array concatenation and slicing to shift the elements, making the operation straightforward in handling and rebuilding the shifted grid.
Calculate Direct Position Mapping: Instead of flattening, calculate the direct position mapping for shifted elements. This avoids the extra space used by intermediate lists.
Perform Element-wise Placement: Iterate through elements and directly place them in their new calculated positions.
Time Complexity: O(m * n).
Space Complexity: O(m * n) for the shifted result.
1JavaScript calculates and directly reallocates values using direct index transformations within the new array during iteration.