Skip to content

Commit 5136258

Browse files
committed
O(m*n) time and o(m*n) space using reverse.
1 parent 71378f5 commit 5136258

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.
3+
4+
In one shift operation:
5+
6+
Element at grid[i][j] moves to grid[i][j + 1].
7+
Element at grid[i][n - 1] moves to grid[i + 1][0].
8+
Element at grid[m - 1][n - 1] moves to grid[0][0].
9+
Return the 2D grid after applying shift operation k times.
10+
11+
12+
13+
Example 1:
14+
15+
16+
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
17+
Output: [[9,1,2],[3,4,5],[6,7,8]]
18+
Example 2:
19+
20+
21+
Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
22+
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
23+
Example 3:
24+
25+
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
26+
Output: [[1,2,3],[4,5,6],[7,8,9]]
27+
28+
29+
Constraints:
30+
31+
m == grid.length
32+
n == grid[i].length
33+
1 <= m <= 50
34+
1 <= n <= 50
35+
-1000 <= grid[i][j] <= 1000
36+
0 <= k <= 100
37+
"""
38+
class Solution:
39+
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
40+
m,n = len(grid), len(grid[0])
41+
k = k % (m*n)
42+
temp = [grid[i][j] for i in range(m) for j in range(n)]
43+
temp = temp[-k:] + temp[:-k]
44+
result = []
45+
for i in range(m):
46+
result.append(temp[i*n:i*n+n])
47+
return result

0 commit comments

Comments
 (0)