Problem 1260

Abstract / Summary

Shift all elements in each row of a grid to the right by one position with the last element wrapping to the first.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1260.py

class Solution:
    def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
        width  = len(grid[0])
        height = len(grid)
        size   = width * height

        # 2D => 1D (zero-based)
        def two2one(x, y):
            return y * width + x

        # 1D => 2D (zero-based)
        def one2two(n):
            x = n %  width
            y = n // width
            return x, y

        # store all values
        all = {}
        for y in range(height):
            for x in range(width):
                all[two2one(x, y)] = grid[y][x]

        # overwrite grid with shifted values
        for y in range(height):
            for x in range(width):
                original = two2one(x, y)
                shifted  = original + k
                shifted %= size
                kx, ky = one2two(shifted)
                grid[ky][kx] = all[original]

        return grid
32 lines | 934 bytes | submitted December 21, 2023 | GitHub   17% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Matrix
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution.shiftGrid method receives a rectangular matrix grid and an integer k. It returns a new arrangement of the matrix where each element is moved k positions forward in row-major order, wrapping around to the beginning when the end is reached. The implementation converts the two-dimensional coordinates to a one-dimensional index, stores the original values in a dictionary, computes the target index for each cell, and writes the shifted values back into the original grid before returning it.

Coordinate conversion

def two2one(x, y):
    return y * width + x

The helper two2one maps a column x and row y to a linear index based on the matrix width. This conversion treats the matrix as a flat list laid out row by row.

def one2two(n):
    x = n %  width
    y = n // width
    return x, y

The inverse helper one2two restores the column and row from a linear index using modulus and integer division. These two functions are central to the shift logic because they allow the algorithm to reason about positions with simple arithmetic.

Capturing the original state

all = {}
for y in range(height):
    for x in range(width):
        all[two2one(x, y)] = grid[y][x]

A dictionary named all is populated with every element of the input matrix, keyed by its linear index. By copying the values before any modifications, the algorithm guarantees that later writes do not overwrite data that is still needed for subsequent shifts. This step isolates the source data from the destination writes.

Computing the shifted location

original = two2one(x, y)
shifted  = original + k
shifted %= size
kx, ky = one2two(shifted)
grid[ky][kx] = all[original]

For each cell, the original linear index is increased by k. The modulo operation with size (the total number of cells) implements the wrap-around behavior, ensuring that indices that exceed the matrix bounds cycle back to the start. The resulting index is converted back to row and column coordinates, and the value stored in all at the original position is written to the computed destination cell.

Edge-case handling

The algorithm naturally accommodates several edge conditions:

  • When k is zero, the modulo operation yields the original index, so each element is written back to its own position, leaving the matrix unchanged.
  • When k equals a multiple of size, the modulo reduces the shift to zero, again resulting in no movement.
  • When k exceeds size, the modulo operation reduces it to an equivalent smaller shift, guaranteeing correct wrap-around without extra loops.
  • Empty rows or columns are not possible because the code assumes at least one element per row (len(grid[0])). The width and height calculations therefore always produce positive integers, and the loops iterate correctly over all existing cells.

Performance optimizations

The implementation avoids repeated recomputation of the matrix size by storing width, height, and size in local variables. The use of simple arithmetic for index translation (y * width + x and %///) is computationally cheap and runs in constant time per cell. By pre-populating the all dictionary, the algorithm eliminates the need for a secondary pass to read values during the write phase; each lookup is an O(1) hash table access. The overall flow touches each element exactly twice-once for copying into the dictionary and once for writing to its new location-resulting in a linear pass over the data without nested recomputation.

Result

After the nested loops complete, the original grid has been transformed in place to reflect the k-step rightward shift, and the method returns this modified matrix. The code achieves the required transformation with clear separation of concerns (index conversion, data capture, and write-back) and leverages dictionary lookups and modular arithmetic to handle wrapping efficiently.

written by openai gpt

ELI5 - Simplified Explanation

Imagine the grid is like a flat game board made of square tiles. Each tile has a special secret number waiting underneath it. The goal is to slide every single number forward by a certain amount of steps, just like pieces moving around a game board.

First, the code measures how wide and tall the board is so it knows exactly how many spaces exist in total. It uses a clever trick to think about the board in two different ways. Sometimes the computer likes to think of the grid as a perfect square with rows and columns, but other times it prefers to imagine the whole thing as one long, skinny line of spaces.

The first helper function turns the location of a tile found at a column and row into a single number on that long line. The second helper function does the opposite by taking a spot on that long line and turning it back into a row and column for the board.

A collection is made to remember every number and exactly where each one is currently sitting so that nothing gets lost. Once the computer is holding all the numbers securely, it starts the sliding process. It looks at each tile, figures out how far the number needs to move, and uses math to calculate where that number should go next. If a number reaches the very end of the line, it wraps back around to the beginning, like a train going through a tunnel and coming out the other side. By the time it finishes, every number has safely moved to its new home on the board.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 6.38 | σ = 1.39

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
qiyuangong Java
suxrobGM C#
withaarzoo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
qiyuangong Java
suxrobGM C#
withaarzoo C++
YuriSpiridonov Python
31 links | 20 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   December 21, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality