#3643
Easy Algorithms Flip square submatrix vertically
Array Two Pointers Matrix
72.9% acceptance
Feb 25, 2026
56
2
You are given an m x n integer matrix grid, and three integers x, y, and k.
The integers x and y represent the row and column indices of the top-left corner of a square submatrix
and the integer k represents the size (side length) of the square submatrix.
Your task is to flip the submatrix by reversing the order of its rows vertically.
Return the updated matrix.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn reverse_submatrix(mut grid: Vec<Vec<i32>>, x: i32, y: i32, k: i32) -> Vec<Vec<i32>> {
let (x, y, k) = (x as usize, y as usize, k as usize);
// Flip the k x k submatrix at top-left (x, y) by reversing row order
for col_off in 0..k {
let col = y + col_off;
let mut top = x;
let mut bot = x + k - 1;
while top < bot {
let tmp = grid[top][col];
grid[top][col] = grid[bot][col];
grid[bot][col] = tmp;
top += 1;
bot -= 1;
}
}
grid
}
}