Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

A vertical flip reverses the selected square's row order without changing the column order inside those rows. Pair its top row with its bottom row, then move inward. Only the selected columns should be swapped.

Approach

For each row offset in the first half of the k rows, pair row x + offset with row x + k - 1 - offset. Swap their entries for columns from y through y + k - 1. Stop after floor(k / 2) row pairs and return the modified grid.

Processing only half the rows prevents swapping each pair twice and undoing the flip. When k is odd, the middle row maps to itself and stays untouched. Cells outside the chosen square are never assigned, and a one-cell square requires no swaps.

class Solution: def reverseSubmatrix(self, grid: List[List[int]], x: int, y: int, k: int) -> List[List[int]]: sub_row = 0 for i in range(x, x + k): if sub_row == (x + k - x) // 2: break for j in range(y, y + k): grid[i][j], grid[x + k - 1 - sub_row][j] = grid[x + k - 1 - sub_row][j], grid[i][j] sub_row += 1 return grid

Complexity analysis

Time: O(k^2). Auxiliary space: O(1) because the matrix is modified in place.