array rotation
2D arrays
matrix manipulation
computer science
algorithm

How do you rotate a two dimensional array?

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

Rotating a two-dimensional array is a common operation in computer science and image processing. This operation involves changing the orientation of an array, which is often used in graphics applications and matrix manipulations. In this article, we will explore different methods to rotate a 2D array, primarily focusing on square matrices, and understand the underlying algorithmic concepts.

Understanding the Basics

A two-dimensional array (or matrix) is a sequence of elements arranged in rows and columns. If the number of rows equals the number of columns, it is known as a square matrix. Rotating a matrix usually involves rotating the elements by 90 degrees clockwise or counterclockwise.

Rotations:

  • 90 Degrees Clockwise:
    • The first row becomes the last column, the second row becomes the second-last column, and so on.
  • 90 Degrees Counterclockwise:
    • The first column becomes the last row, the second column becomes the second-last row, and so on.
  • 180 Degrees:
    • A combination of two 90-degree clockwise or counterclockwise rotations.

Algorithm for 90-Degree Clockwise Rotation

To rotate an N x N matrix by 90 degrees clockwise, we can follow these steps:

  1. Transpose the Matrix:
    • Swap elements matrix[i][j] with matrix[j][i] for all i, j.
  2. Reverse Each Row:
    • After the transposition, reverse each row to achieve the final rotated matrix.

Code Example - 90 Degrees Clockwise Rotation

Below is an example in Python to illustrate this process:

python
1def rotate_90_clockwise(matrix):
2    n = len(matrix)
3    
4    # Transpose the matrix
5    for i in range(n):
6        for j in range(i, n):
7            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
8    
9    # Reverse each row
10    for i in range(n):
11        matrix[i].reverse()
12
13    return matrix
14
15# Example usage
16matrix = [
17    [1, 2, 3],
18    [4, 5, 6],
19    [7, 8, 9]
20]
21
22rotated_matrix = rotate_90_clockwise(matrix)

Algorithm for 90-Degree Counterclockwise Rotation

For a 90-degree counterclockwise rotation, the steps are as follows:

  1. Transpose the Matrix:
    • Swap elements matrix[i][j] with matrix[j][i].
  2. Reverse Each Column:
    • After transposition, reverse each column to get the final rotated matrix.

Code Example - 90 Degrees Counterclockwise Rotation

Here is the Python code to achieve a counterclockwise rotation:

python
1def rotate_90_counterclockwise(matrix):
2    n = len(matrix)
3    
4    # Transpose the matrix
5    for i in range(n):
6        for j in range(i, n):
7            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
8    
9    # Reverse each column
10    for j in range(n):
11        for i in range(n // 2):
12            matrix[i][j], matrix[n - 1 - i][j] = matrix[n - 1 - i][j], matrix[i][j]
13    
14    return matrix
15
16# Example usage
17matrix = [
18    [1, 2, 3],
19    [4, 5, 6],
20    [7, 8, 9]
21]
22
23rotated_matrix = rotate_90_counterclockwise(matrix)

Summarizing Key Operations

Below is a table summarizing the steps involved in matrix rotations:

Rotation TypeMain Steps
90 Degrees ClockwiseTranspose Reverse Each Row
90 Degrees CounterclockwiseTranspose Reverse Each Column
180 DegreesRotate 90 Degrees Twice

Considerations and Complexity

  • Time Complexity: The above methods run in O(N2)O(N^2) time, where NN is the number of rows or columns in the matrix. This is because each element of the matrix is accessed a constant number of times.
  • Space Complexity: These approaches use O(1)O(1) additional space, modifying the matrix in place.

Extensions

Apart from the discussed techniques, rotating non-square matrices or rotating by angles other than multiples of 90 degrees typically requires different approaches, often involving computationally heavier operations.

  • Non-Square Matrices: Special handling is required, and such rotations are typically approached by translating the transformations into a linear algebra context.
  • Arbitrary Angles: Rotations at arbitrary angles are beyond simple index manipulation and require interpolation techniques, especially in the context of graphical transformations.

This comprehensive understanding of rotating two-dimensional arrays equips you to tackle a variety of problems in competitive programming, game development, and real-world applications of data transformation.


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.