LeetCode 1260: Shift 2D Grid

LeetCode 1260 Solution 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.

LeetCode 1260 Solutions in Java, C++, Python

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;
    }
}

Interactive Code Editor for LeetCode 1260

Improve Your LeetCode 1260 Solution

Use the editor below to refine the provided solution for LeetCode 1260. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems