Algorithms · Visualized
Matrix: Transpose
Matrix & 2D
Rotations, traversals, and grid searches on 2D arrays.
Transposing a matrix flips it over its main diagonal: the element at row i, column j moves to row j, column i. Time: O(m×n) average, O(m×n) — every cell is read once worst; space: O(1) for a square matrix in place; O(m×n) when a rectangular result must be allocated.
Big-O: Classic O(m·n) sweeps and in-place tricks.
Transpose a Matrix
Matrix / 2D ArrayTransposing a matrix flips it over its main diagonal: the element at row i, column j moves to row j, column i. Rows become columns and columns become rows, so an m×n matrix becomes n×m. For a square matrix the swap can be done in place by exchanging only the cells above the diagonal with their mirror cells below it.
How Transpose Works
- Read the dimensions: an m×n input produces an n×m output, so the result cannot alias the original unless the matrix is square.
- For a square matrix, loop i from 0 to n-1 and j from i+1 to n-1, swapping a[i][j] with a[j][i]. Starting j at i+1 skips the diagonal (which stays put) and avoids swapping each pair twice.
- For a rectangular matrix, allocate an n×m result and copy a[i][j] into result[j][i] for every cell.
- After the pass, position (i, j) of the result holds the input's (j, i) value; the diagonal itself is unchanged.
Transpose Worked Example
Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Swap (0,1)=2 with (1,0)=4 → [[1,4,3],[2,5,6],[7,8,9]]. Swap (0,2)=3 with (2,0)=7. Swap (1,2)=6 with (2,1)=8. Final transpose: [[1,4,7],[2,5,8],[3,6,9]].
def transpose_matrix(m):
return [list(row) for row in zip(*m)]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Transpose Time & Space Complexity
When to Use Transpose
- Preparing image or sensor grids for algorithms that expect channels or features along the other axis.
- Building block for in-place rotation and for symmetry checks such as a matrix being equal to its transpose.
- Converting between row-major and column-major layouts when exchanging data with other libraries.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.