Skip to main content
Back to problems
Leetcode
Medium
Arrays
Matrices
1260. Shift 2D Grid

Shift every element in a 2D grid to the right by kk positions, wrapping across rows as needed.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Shift 2D Grid

gfg
Problem Statement

Problem

You are given an m×nm \times n grid of integers and a non-negative integer kk.

Perform a cyclic shift of the grid to the right by kk positions:

  • Moving right from the last column of a row continues at the first column of the next row.
  • Moving right from the last element of the grid continues at the first element of the grid.

Return the resulting grid after all shifts.

Intuition

This is a 2D indexing and simulation problem. One practical way to solve it is to treat the grid as a flattened array of length mnm \cdot n, shift indices by kk, and then map the result back into 2D form.

Input Format

  • The first line contains two integers mm and nn.
  • The next mm lines each contain nn integers describing the grid.
  • The last line contains an integer kk.

Output Format

  • Return the shifted grid as an m×nm \times n matrix of integers.

Constraints

  • 1m,n501 \le m, n \le 50
  • 0k1050 \le k \le 10^5
  • Grid values fit in 32-bit signed integers
Examples
Sample cases returned by the problem API.

Example 1

Input

grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1

Output

[[9,1,2],[3,4,5],[6,7,8]]

Explanation

A shift by 1 moves each element one step to the right in row-major order, with the last element wrapping to the front.

Example 2

Input

grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4

Output

[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]

Explanation

A shift by 4 is equivalent to moving every row down by one row in flattened order.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.