Install our extension to search inside any video instantly.

leetcode 1260 | Shift 2D Grid | 2d to 1d mapping | Leetcode potd

Added:
376 views12likes16:13Code.withvik4Original Release: 2026-07-20

The Shift 2D Grid problem can be efficiently solved by converting the 2D grid to a 1D array, rotating it by k positions using modulo arithmetic, and then converting back to 2D. The key insight is that shifting a 2D grid right by k positions is mathematically equivalent to rotating a 1D array by k positions. For an element at position (i, j) in an m×n grid, its 1D index is i×n + j. After rotating by k positions, the new 1D index becomes (i×n + j + k) % (m×n). This new index can then be converted back to 2D coordinates using row = new_index / n and column = new_index % n. This approach reduces time complexity from O(m×n×k) to O(m×n) by avoiding repeated simulation of each shift operation.