Rotate a square matrix 90 degrees
Rotate a square matrix 90 degrees clockwise in place.
Course progress
Problem 100 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Expected output
7 4 1 8 5 2 9 6 3
What is happening?
Transpose rows into columns, then reverse each row. The original bottom-left 7 becomes the new top-left value, producing the clockwise rotation.
Solution strategy
Build the right mental model
Transpose the matrix across its main diagonal, then reverse every row to complete the clockwise rotation.
Core concepts
matrix · in-place transformation
Complexity
Time O(n^2), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for rotate-matrix-90-degrees
using System;
class Program
{
static void Rotate(int[,] matrix)
{
int size = matrix.GetLength(0);
if (size != matrix.GetLength(1)) throw new ArgumentException("Matrix must be square.");
for (int row = 0; row < size; row++)
for (int column = row + 1; column < size; column++)
{
int temporary = matrix[row, column];
matrix[row, column] = matrix[column, row];
matrix[column, row] = temporary;
}
for (int row = 0; row < size; row++)
for (int left = 0, right = size - 1; left < right; left++, right--)
{
int temporary = matrix[row, left];
matrix[row, left] = matrix[row, right];
matrix[row, right] = temporary;
}
}
static void Main()
{
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Rotate(matrix);
for (int row = 0; row < 3; row++)
{
for (int column = 0; column < 3; column++)
Console.Write((column == 0 ? "" : " ") + matrix[row, column]);
Console.WriteLine();
}
}
}Knowledge check
Questions students often ask
What is the main idea behind rotate a square matrix 90 degrees?
Transpose the matrix across its main diagonal, then reverse every row to complete the clockwise rotation.
What is the time and space complexity of this solution?
Time O(n^2), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.