Magicsheet logo

Shift 2D Grid

Easy
25%
Updated 8/1/2025

Asked by 1 Company

Shift 2D Grid

What is this problem about?

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.

Why is this asked in interviews?

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.

Algorithmic pattern used

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].

Example explanation

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.

Common mistakes candidates make

  • Applying k shifts one by one — O(k × m × n) is too slow when k is large; use k % total directly.
  • Incorrect reshape: reshaping a flat array of length m*n into m rows of n uses flat[i*n : (i+1)*n] for row i.
  • Off-by-one in the rotation: right shift by k takes the last k elements to the front — flat[-k:] + flat[:-k] in Python (or flat[total-k:] + flat[:total-k]).
  • Not reducing k modulo m*n first — large k values should be reduced to avoid unnecessary work.

Interview preparation tip

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.

Similar Questions