Skip to content

Instantly share code, notes, and snippets.

@jineshqa
Created May 29, 2026 05:41
Show Gist options
  • Select an option

  • Save jineshqa/a841db7fa0f2e4cb8e9535cdb20c3474 to your computer and use it in GitHub Desktop.

Select an option

Save jineshqa/a841db7fa0f2e4cb8e9535cdb20c3474 to your computer and use it in GitHub Desktop.
Image rotation

Matrix Manipulation Mastery

A Professional Reference for In-Place Algorithms


1. Core Manipulation Primitives

Operation Logic Python Code Implementation
Diagonal Flip (Transpose) Swap row/col across the main diagonal. for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
Horizontal Axis Flip (Vertical Reflection) Swap entire rows from top to bottom. for i in range(n // 2):
matrix[i], matrix[n-1-i] = matrix[n-1-i], matrix[i]
Vertical Axis Flip (Horizontal Reflection) Swap columns within each row from left to right. for i in range(n):
for j in range(n // 2):
matrix[i][j], matrix[i][n-1-j] = matrix[i][n-1-j], matrix[i][j]

2. Rotation "Cheat Codes"

To rotate a matrix in-place, perform these fundamental flips in sequence:

  • 90° Clockwise:
    1. Diagonal Flip (Transpose)
    2. Vertical Axis Flip (Horizontal Reflection)
  • 180° Rotation:
    1. Horizontal Axis Flip (Vertical Reflection)
    2. Vertical Axis Flip (Horizontal Reflection)
  • 270° Clockwise (or 90° Counter-Clockwise):
    1. Diagonal Flip (Transpose)
    2. Horizontal Axis Flip (Vertical Reflection)

3. Critical Logic Triggers

The Stop Condition (n // 2)

Essential for all reflection operations. Since you are swapping two elements at once, you only need to visit half the length. If you iterate through the full length, you perform a "double-swap," which returns the matrix to its original state.

The Mirror Index (n - 1 - j)

This mathematical formula finds the element's partner on the opposite side of the axis. The sum of an index and its mirror partner always equals the maximum index ($n - 1$).

  • When $j = 0$, partner is $n - 1$.
  • When $j = 1$, partner is $n - 2$.

The Transpose Skip (j = i + 1)

In a diagonal flip, starting the inner loop at i + 1 ensures you skip the elements on the diagonal (which don't move) and only visit the "upper triangle." This prevents redundant swaps that would undo the transposition.

The "Anti-Diagonal" Flip (Secondary Diagonal)

If a problem asks to flip over the line from the top-right to bottom-left:

  • Formula: matrix[i][j] $\leftrightarrow$ matrix[n - 1 - j][n - 1 - i]

Reference for Coding Interviews & Algorithm Design

Comments are disabled for this gist.