mediumDSA

How do you rotate an N×N matrix by 90 degrees in place?

708 views
01

Understand the problem

Explain in-place matrix rotation.

matrixin-place
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Transpose then reverse rows
Run Playground
def rotate(matrix):
    n = len(matrix)
    for i in range(n):                 # transpose (upper triangle)
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    for row in matrix:                 # reverse each row
        row.reverse()
    return matrix


# --- demo ---
print(rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
# [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.