Shift 2D Grid — LeetCode 1260 Python Solution
EasyArrayMatrixSimulation
- Problem
- #1260
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.
Example
- Input
- grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
- Output
- [[9,1,2],[3,4,5],[6,7,8]]
Python solution
Python
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
ans = [[0] * n for _ in range(m)]
for i, row in enumerate(grid):
for j, v in enumerate(row):
x, y = divmod((i * n + j + k) % (m * n), n)
ans[x][y] = v
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n), where m and n are the number of rows and columns in the `grid` array, respectively |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1260. Shift 2D Grid is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1260. Shift 2D Grid?
- LeetCode 1260. Shift 2D Grid is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1260. Shift 2D Grid?
- The Python solution on this page runs in O(m \times n), where m and n are the number of rows and columns in the `grid` array, respectively.
- What is the space complexity of LeetCode 1260. Shift 2D Grid?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1260. Shift 2D Grid cover?
- LeetCode 1260. Shift 2D Grid is tagged Array, Matrix and Simulation on LeetCode.