Transpose Matrix

EasyMatrixindex swap

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a 2D integer grid matrix, return its **transpose**. The transpose of a matrix is formed by flipping it over its main diagonal: the element located at row r and column c in the original moves to row c and column r in the result. As a consequence, the rows of the input become the columns of the output (and vice versa). If the input has dimensions m x n (that is, m rows and n columns), the transposed matrix will have dimensions n x m. Note that the result is not guaranteed to be square, so you should build a new grid rather than swapping entries in place.

Examples

Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
The input has 2 rows and 3 columns, so the transpose has 3 rows and 2 columns. Original row [1,2,3] becomes the first column, and original row [4,5,6] becomes the second column.
Input: matrix = [[1,2],[3,4],[5,6]]
Output: [[1,3,5],[2,4,6]]
A 3x2 grid transposes into a 2x3 grid. Each original row turns into a column of the answer.
Input: matrix = [[7]]
Output: [[7]]
A single-element matrix is its own transpose.

Constraints

  • `m == matrix.length`
  • `n == matrix[i].length`
  • `1 <= m, n <= 1000`
  • `1 <= m * n <= 100000`
  • `-10^9 <= matrix[i][j] <= 10^9`
  • Every row of `matrix` has the same length `n`.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.