Flip Square Submatrix Vertically

easy array two pointers matrix

Problem

Given an m × n matrix grid and three integers x, y, k: the cell (x, y) is the top-left corner of a k × k square submatrix. Flip that square vertically — reverse the order of its rows — and return the updated matrix. The cells outside the square stay untouched.

Inputgrid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], x = 1, y = 0, k = 3
Output[[1,2,3,4],[13,14,15,8],[9,10,11,12],[5,6,7,16]]
The 3×3 block spans rows 1–3, columns 0–2. Its top row [5,6,7] and bottom row [13,14,15] swap; the middle row [9,10,11] stays. Cells outside the block (column 3) are unchanged.

def reverseSubmatrix(grid, x, y, k):
    top, bottom = x, x + k - 1          # two row pointers
    while top < bottom:                 # walk inward until they meet
        for c in range(y, y + k):       # swap the k columns of the block
            grid[top][c], grid[bottom][c] = grid[bottom][c], grid[top][c]
        top += 1                        # move top down
        bottom -= 1                     # move bottom up
    return grid
function reverseSubmatrix(grid, x, y, k) {
  let top = x, bottom = x + k - 1;            // two row pointers
  while (top < bottom) {                      // walk inward until they meet
    for (let c = y; c < y + k; c++) {         // swap the k columns of the block
      const t = grid[top][c];
      grid[top][c] = grid[bottom][c];
      grid[bottom][c] = t;
    }
    top++;                                     // move top down
    bottom--;                                  // move bottom up
  }
  return grid;
}
int[][] reverseSubmatrix(int[][] grid, int x, int y, int k) {
    int top = x, bottom = x + k - 1;           // two row pointers
    while (top < bottom) {                      // walk inward until they meet
        for (int c = y; c < y + k; c++) {       // swap the k columns of the block
            int t = grid[top][c];
            grid[top][c] = grid[bottom][c];
            grid[bottom][c] = t;
        }
        top++;                                  // move top down
        bottom--;                               // move bottom up
    }
    return grid;
}
vector<vector<int>> reverseSubmatrix(vector<vector<int>>& grid, int x, int y, int k) {
    int top = x, bottom = x + k - 1;           // two row pointers
    while (top < bottom) {                      // walk inward until they meet
        for (int c = y; c < y + k; c++) {       // swap the k columns of the block
            swap(grid[top][c], grid[bottom][c]);
        }
        top++;                                  // move top down
        bottom--;                               // move bottom up
    }
    return grid;
}
Time: O(k²) Space: O(1)