You are given a 2D grid of integers and an integer k. You need to shift the grid k times. In one shift operation:
grid[i][j]
moves to grid[i][j + 1]
.Return the 2D grid after performing k shift operations.
Example:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
Constraints:
m == grid.length
n == grid[i].length
1 <= m <= 50
1 <= n <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100
k
is zero, the grid should be returned as is.-1000
and 1000
, and our operations do not need to handle them differently.k % (m * n)
to optimize the number of actual shifts needed.k
shifts by computing k % total_elements
.from typing import List
def shiftGrid(grid: List[List[int]], k: int) -> List[List[int]]:
# Get dimensions of the grid
m, n = len(grid), len(grid[0])
# Flatten the grid
flat_grid = [grid[i][j] for i in range(m) for j in range(n)]
# Total number of elements in the grid
total_elements = m * n
# Optimize k
k = k % total_elements
if k == 0:
return grid
# Perform the shift
flat_grid = flat_grid[-k:] + flat_grid[:-k]
# Reconstruct the shifted grid
new_grid = [
[flat_grid[i * n + j] for j in range(n)]
for i in range(m)
]
return new_grid
# Example usage
grid = [[1,2,3],[4,5,6],[7,8,9]]
k = 1
print(shiftGrid(grid, k)) # Output: [[9,1,2],[3,4,5],[6,7,8]]
Thus, the overall time complexity is O(m*n)
, which is efficient given the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?