The Shift 2D Grid interview question gives you an m×n 2D grid and an integer k. Shift the grid to the right by k positions: each element at (i, j) moves to (i, (j+1) % n), with wrap-around to the next row and eventually back to the top-left. After k such shifts, return the resulting grid. This is a matrix simulation with index arithmetic.
Amazon asks this beginner-level simulation problem to test 2D index arithmetic and the ability to convert between flat (1D) and 2D coordinates. The key insight is treating the grid as a 1D array of length m×n, shifting by k positions with wrap-around modulo m×n, then reshaping back into 2D. This models circular buffer shifting, image scrolling, and memory layout transformations.
The pattern is flatten + rotate + reshape. Flatten the 2D grid into a 1D array of length total = m * n. A shift of k is equivalent to rotating the 1D array right by k % total positions: rotated = flat[total - k :] + flat[: total - k]. Then reshape back into m rows of n elements each. This is O(m×n) time and O(m×n) space. Alternatively, compute directly: element at position p in the flat array moves to position (p + k) % total, so new_grid[(p + k) // n][(p + k) % n] = old_flat[p].
Grid:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
k = 1. Flatten: [1,2,3,4,5,6,7,8,9]. Shift right by 1: [9,1,2,3,4,5,6,7,8]. Reshape:
[[9, 1, 2],
[3, 4, 5],
[6, 7, 8]]
k = 9 (full cycle): same as k=0, returns original grid.
k % total directly.m*n into m rows of n uses flat[i*n : (i+1)*n] for row i.flat[-k:] + flat[:-k] in Python (or flat[total-k:] + flat[:total-k]).m*n first — large k values should be reduced to avoid unnecessary work.For the Shift 2D Grid coding problem, the matrix array simulation interview pattern is solved cleanly by treating the 2D grid as a 1D circular buffer. In Python, flat[-k:] + flat[:-k] rotates a list right by k in one line. Amazon interviewers use this as a 5-minute warm-up — solve it cleanly in under 3 minutes with the flatten-rotate-reshape approach, then discuss follow-ups like "how would you do this in-place?" The in-place reverse-based array rotation is a classic technique worth knowing.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Reshape the Matrix | Easy | Solve | |
| Convert 1D Array Into 2D Array | Easy | Solve | |
| Transpose Matrix | Easy | Solve | |
| Available Captures for Rook | Easy | Solve | |
| Zigzag Grid Traversal With Skip | Easy | Solve |