Transpose a matrix
Transpose a rectangular integer matrix so that each original row becomes a column.
Course progress
Problem 37 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]]
Expected output
1 4 2 5 3 6
What is happening?
Rows become columns: the first column is 1,4, the second is 2,5, and the third is 3,6.
Solution strategy
Build the right mental model
Create a result whose row and column counts are swapped, then assign result[column, row] from input[row, column].
Core concepts
matrices · nested loops
Complexity
Time O(rows x columns), space O(rows x columns).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for matrix-transpose
using System;
class Program
{
static int[,] Transpose(int[,] matrix)
{
int rows = matrix.GetLength(0);
int columns = matrix.GetLength(1);
int[,] result = new int[columns, rows];
for (int row = 0; row < rows; row++)
for (int column = 0; column < columns; column++)
result[column, row] = matrix[row, column];
return result;
}
static void Main()
{
int[,] result = Transpose(new int[,] { { 1, 2, 3 }, { 4, 5, 6 } });
for (int row = 0; row < result.GetLength(0); row++)
{
for (int column = 0; column < result.GetLength(1); column++)
Console.Write((column == 0 ? "" : " ") + result[row, column]);
Console.WriteLine();
}
}
}Knowledge check
Questions students often ask
What is the main idea behind transpose a matrix?
Create a result whose row and column counts are swapped, then assign result[column, row] from input[row, column].
What is the time and space complexity of this solution?
Time O(rows x columns), space O(rows x columns).
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.