3643. Flip Square Submatrix Vertically
Approach
For each cell determine flip parity from range queries applied; XOR result.
Key Techniques
Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.
Dynamic programming solves problems by breaking them into overlapping sub-problems and storing results to avoid redundant work. The key steps are: define state, write a recurrence relation, set base cases, and choose top-down (memoization) or bottom-up (tabulation). DP often yields O(n²) → O(n) time improvements over brute force.
Matrix problems often involve BFS/DFS flood fill, dynamic programming on 2D grids, or spiral/diagonal traversal. For row × column DP, break it into 1D sub-problems column by column. Common pitfalls: boundary checks and modifying the input matrix in-place.
// Approach: For each cell determine flip parity from range queries applied; XOR result.
// Time: O(n * k) Space: O(n²)
public class Solution
{
public int[][] ReverseSubmatrix(int[][] grid, int x, int y, int k)
{
// Iterate through the first half of the rows in the submatrix
for (int row = x; row < x + k / 2; row++)
{
// Calculate the corresponding row from the bottom to swap with
int mirrorRow = x + k - 1 - (row - x);
// Swap all elements in the current row with the mirror row
for (int col = y; col < y + k; col++)
{
// Perform the swap using a temporary variable
int temp = grid[row][col];
grid[row][col] = grid[mirrorRow][col];
grid[mirrorRow][col] = temp;
}
}
return grid;
}
}