#3643

Flip Square Submatrix Vertically

Easy
ArrayTwo PointersMatrixArrayMatrix Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(k)
Space
O(1)
O(1)
💡

Intuition

Time O(k)Space O(1)

Using two pointers, we can efficiently swap rows in the submatrix without needing extra space. This reduces unnecessary iterations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two pointers, one at the top of the submatrix and one at the bottom.
  2. 2Step 2: Swap the rows pointed by the two pointers for the specified columns.
  3. 3Step 3: Move the pointers towards the center until they meet.
solution.py4 lines
1def flipSubmatrix(grid, x, y, k):
2    for i in range(k // 2):
3        grid[x + i], grid[x + k - 1 - i] = grid[x + k - 1 - i], grid[x + i]
4    return grid

Complexity note: The complexity is O(k) since we only iterate through half of the k rows to perform the swaps.

  • 1Flipping a submatrix is similar to reversing an array.
  • 2Two pointers can optimize the swapping process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.