matrix rotation
2D array
algorithm
90 degree rotation
duplicate question

Rotate MN Matrix 90 degrees

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Rotating a matrix by 90 degrees is a common interview and data-processing problem. The key detail is whether the matrix is square or rectangular, because an M x N matrix changes shape when you rotate it.

Understand the Index Mapping

For a clockwise rotation, an element at row r and column c moves to:

  • new row c
  • new column rows - 1 - r

That means a matrix with rows by cols becomes cols by rows.

Start with this input:

text
1  2  3  4
5  6  7  8
9 10 11 12

After a 90-degree clockwise rotation, the result is:

text
19 5 1
210 6 2
311 7 3
412 8 4

Notice that the output now has 4 rows and 3 columns. That is why a general M x N rotation usually creates a new matrix instead of modifying the original in place.

A Simple Python Solution

The most direct approach is to allocate a result matrix with swapped dimensions and copy elements into their rotated positions.

python
1def rotate_clockwise(matrix):
2    if not matrix or not matrix[0]:
3        return []
4
5    rows = len(matrix)
6    cols = len(matrix[0])
7    result = [[0] * rows for _ in range(cols)]
8
9    for r in range(rows):
10        for c in range(cols):
11            result[c][rows - 1 - r] = matrix[r][c]
12
13    return result
14
15
16matrix = [
17    [1, 2, 3, 4],
18    [5, 6, 7, 8],
19    [9, 10, 11, 12],
20]
21
22for row in rotate_clockwise(matrix):
23    print(row)

Output:

text
1[9, 5, 1]
2[10, 6, 2]
3[11, 7, 3]
4[12, 8, 4]

This algorithm is easy to verify because every input cell is written exactly once to its new location.

A Compact Pythonic Version

If readability matters more than showing the index math explicitly, Python gives you a neat shortcut with zip.

python
1def rotate_clockwise_zip(matrix):
2    return [list(row) for row in zip(*matrix[::-1])]
3
4
5matrix = [
6    [1, 2, 3],
7    [4, 5, 6],
8]
9
10print(rotate_clockwise_zip(matrix))

This works because:

  • 'matrix[::-1] reverses the row order'
  • 'zip(*...) transposes the reversed matrix'

For interviews or production code in teams with mixed experience, the explicit nested-loop version is often easier to maintain.

Counterclockwise Rotation

For a 90-degree counterclockwise rotation, the mapping changes. One practical implementation is:

python
1def rotate_counterclockwise(matrix):
2    if not matrix or not matrix[0]:
3        return []
4
5    rows = len(matrix)
6    cols = len(matrix[0])
7    result = [[0] * rows for _ in range(cols)]
8
9    for r in range(rows):
10        for c in range(cols):
11            result[cols - 1 - c][r] = matrix[r][c]
12
13    return result

The important idea is not memorizing a trick, but understanding that rotation is just coordinate remapping.

Can You Rotate In Place

Only square matrices can be rotated in place without changing the container dimensions. For a 3 x 3 matrix, you can rotate layer by layer because the result is still 3 x 3. For a 3 x 4 matrix, in-place rotation is not a natural fit because the output must be 4 x 3.

That is why many answers online say "transpose and reverse rows" for square matrices. That method is excellent for N x N, but it does not solve the general rectangular case unless you are willing to build a new result.

Common Pitfalls

  • Assuming an M x N matrix stays the same shape after rotation. A clockwise 90-degree rotation becomes N x M.
  • Trying to do the rectangular case in place. That usually complicates the solution for no benefit.
  • Mixing up clockwise and counterclockwise formulas. Test with a small 2 x 3 example so mistakes are obvious.
  • Forgetting to handle empty input or ragged rows. A matrix algorithm should either validate rectangular shape or document the requirement clearly.
  • Using a clever one-liner without understanding the mapping. That makes debugging harder when the rotation direction is wrong.

Summary

  • Rotating a rectangular matrix by 90 degrees changes its dimensions from M x N to N x M.
  • The safest general solution is to allocate a new matrix and copy elements to rotated coordinates.
  • For clockwise rotation, result[c][rows - 1 - r] = matrix[r][c] is the core mapping.
  • Python's zip solution is concise, but the explicit loop is easier to reason about.
  • In-place rotation is mainly a square-matrix technique, not a general rectangular-matrix solution.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.