LeetCode 1260: Shift 2D Grid Solution

Master LeetCode problem 1260 (Shift 2D Grid), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1260. Shift 2D Grid

Problem Explanation

Explanation

To shift the 2D grid k times, we can first flatten the grid into a 1D list, then perform the shifts in this 1D list, and finally reshape the list back into the original 2D grid shape. Shifting k times is equivalent to shifting k % (m * n) times.

  1. Flatten the grid into a 1D list.
  2. Perform k shifts on the 1D list.
  3. Reshape the modified 1D list back into the 2D grid shape.

Time complexity: O(m * n) where m is the number of rows and n is the number of columns in the grid. Space complexity: O(m * n) for storing the flattened grid.

Solution Code

class Solution {
    public List<List<Integer>> shiftGrid(int[][] grid, int k) {
        int m = grid.length;
        int n = grid[0].length;
        
        List<List<Integer>> result = new ArrayList<>();
        
        // Flatten the grid into a 1D list
        List<Integer> flatGrid = new ArrayList<>();
        for (int[] row : grid) {
            for (int num : row) {
                flatGrid.add(num);
            }
        }
        
        // Perform k shifts on the 1D list
        k = k % (m * n);
        Collections.rotate(flatGrid, k);
        
        // Reshape the modified 1D list back into the 2D grid shape
        for (int i = 0; i < m; i++) {
            List<Integer> row = new ArrayList<>();
            for (int j = 0; j < n; j++) {
                row.add(flatGrid.get(i * n + j));
            }
            result.add(row);
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1260 (Shift 2D Grid)?

This page provides optimized solutions for LeetCode problem 1260 (Shift 2D Grid) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1260 (Shift 2D Grid)?

The time complexity for LeetCode 1260 (Shift 2D Grid) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1260 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1260 in Java, C++, or Python.

Back to LeetCode Solutions