Show problems as
Classic problem #867EasyArrayMatrixSimulation

Transpose Matrix

Real-world version: Flip a Reading Grid Onto Its Side
Tracked in this browser only
Read Transpose Matrix on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A logging rig writes its readings into matrix, a rectangle with one row per sensor and one column per sample instant.

The analysis stage wants the same readings laid out the other way round: one row per sample instant and one column per sensor. Mirror the rectangle across the line running from its top-left corner down and to the right, so the reading stored at row r, column c ends up at row c, column r.

Return the mirrored rectangle.

Examples

Example 1

Input
matrix = [[9, -4, 6], [2, 8, -1]]
Output
[[9, 2], [-4, 8], [6, -1]]

The rig had two sensors and three sample instants, so the answer has three rows of two readings. The reading 6 sat at row 0, column 2 and now sits at row 2, column 0.

Example 2

Input
matrix = [[4], [5], [6]]
Output
[[4, 5, 6]]

Three sensors sampled once each. Mirroring turns the single column into a single row.

Example 3

Input
matrix = [[2, 6], [8, 3]]
Output
[[2, 8], [6, 3]]

The two readings on the mirror line, 2 and 3, stay where they are, and 6 and 8 trade places.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 1000
  • 1 <= m * n <= 10^5
  • -10^9 <= matrix[i][j] <= 10^9

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def transpose(matrix: list[list[int]]) -> list[list[int]]:
Java
public int[][] transpose(int[][] matrix)