00:00

Problem Statement

Input/Output Examples

Visual Explanation

Transposing mirrors the matrix across its main diagonal, and reversing the rows mirrors it left to right. Two mirror images combine into a rotation.

Approaches

Both approaches rotate in place. One combines two simple passes; the other moves four cells at a time ring by ring.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the side length. Both approaches touch each of the n² cells a constant number of times and use one temporary variable.

Interview Tips and Recommended Approach

  • Know both directions. Clockwise: transpose + reverse rows. Counter-clockwise: transpose + reverse columns.
  • Transpose only above the diagonal. Looping over every cell swaps each pair twice.
  • The matrix must be square for an in-place rotation.
  • Explain the ring method if asked for a single-pass solution.

Recommended Approach: Transpose, Then Reverse Rows

Why: it splits the rotation into two well-known operations, each easy to write and verify, with no extra memory.