← Back to libraryQuestion 105 of 273
⌨️Java CodingAdvanced

Rotate a Matrix 90 Degrees Clockwise

📌 Definition:

Rotate a square matrix 90 degrees clockwise in place (e.g. the top row becomes the right column).

📖 Detailed Explanation:

The clean trick is two steps: transpose the matrix (swap across the main diagonal), then reverse each row. This yields a clockwise rotation using O(1) extra space. O(n^2) time.

💻 Solutions:
public static void rotate(int[][] m) {
    int n = m.length;
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++) {
            int t = m[i][j]; m[i][j] = m[j][i]; m[j][i] = t;
        }
    for (int[] row : m)
        for (int l = 0, r = n - 1; l < r; l++, r--) {
            int t = row[l]; row[l] = row[r]; row[r] = t;
        }
}
function rotate(m) {
  const n = m.length;
  for (let i = 0; i < n; i++)
    for (let j = i + 1; j < n; j++)
      [m[i][j], m[j][i]] = [m[j][i], m[i][j]];
  for (const row of m) row.reverse();
  return m;
}
def rotate(m):
    n = len(m)
    for i in range(n):
        for j in range(i + 1, n):
            m[i][j], m[j][i] = m[j][i], m[i][j]
    for row in m:
        row.reverse()
    return m
🔑 Key Points:
  • Transpose, then reverse each row = clockwise
  • Reverse each column instead for counter-clockwise
  • In place, O(1) extra space
  • O(n^2) time
🌍 Real-World Example:

Image rotation and board-game/tetris transforms rely on exactly this in-place rotation; it also tests whether you can compose simpler operations.

🎯 Scenario-Based Interview Question:

How would you change the two-step recipe to rotate counter-clockwise instead?