Transpose Matrix

Easy
#0821Time: O(R * C), where `R` is the number of rows and `C` is the number of columns. We need to iterate through each of the `R * C` elements of the matrix once to perform the transposition.Space: O(R * C), where `R` is the number of rows and `C` is the number of columns. We create a new matrix of size `C x R` to store the result. The space required is proportional to the number of elements in the matrix.2 companies
Data structures

Prompt

Given a 2D integer array matrix, return the transpose of matrix.

The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

 

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]

Example 2:

Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]

 

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 1000
  • 1 <= m * n <= 105
  • -109 <= matrix[i][j] <= 109

Approaches

1 approach with complexity analysis and trade-offs.

The most straightforward and optimal approach is to directly construct the transposed matrix based on its definition. The transpose of a matrix is formed by turning all the rows of a given matrix into columns and vice-versa. This means the element at row i and column j in the original matrix moves to row j and column i in the new matrix. This approach creates a new matrix with swapped dimensions and fills it by iterating through the original matrix.

Algorithm

  1. Get the dimensions of the input matrix: R rows and C columns.
  2. Create a new result matrix, transposedMatrix, with dimensions C rows and R columns.
  3. Iterate through the original matrix using nested loops. The outer loop iterates through rows r from 0 to R-1, and the inner loop iterates through columns c from 0 to C-1.
  4. In each iteration, copy the element matrix[r][c] to transposedMatrix[c][r].
  5. After the loops complete, return the transposedMatrix.

Walkthrough

This method involves creating a new matrix with dimensions n x m, where the original matrix has dimensions m x n. We then iterate through each element of the original matrix and place it in its new position in the transposed matrix.

Here's the step-by-step algorithm:

  1. Determine the dimensions of the input matrix. Let's say it has R rows and C columns.
  2. Create a new result matrix, transposedMatrix, with dimensions C x R.
  3. Iterate through the original matrix with two nested loops. The outer loop runs from r = 0 to R-1 (for rows), and the inner loop runs from c = 0 to C-1 (for columns).
  4. For each element matrix[r][c], assign it to the corresponding position in the new matrix: transposedMatrix[c][r] = matrix[r][c].
  5. After the loops complete, the transposedMatrix will hold the transposed version of the input matrix. Return transposedMatrix.

For example, if matrix[0][1] is 2, it will be placed at result[1][0].

class Solution {    public int[][] transpose(int[][] matrix) {        int R = matrix.length;        if (R == 0) {            return new int[0][0];        }        int C = matrix[0].length;                int[][] transposedMatrix = new int[C][R];                for (int r = 0; r < R; r++) {            for (int c = 0; c < C; c++) {                transposedMatrix[c][r] = matrix[r][c];            }        }                return transposedMatrix;    }}

Complexity

Time

O(R * C), where `R` is the number of rows and `C` is the number of columns. We need to iterate through each of the `R * C` elements of the matrix once to perform the transposition.

Space

O(R * C), where `R` is the number of rows and `C` is the number of columns. We create a new matrix of size `C x R` to store the result. The space required is proportional to the number of elements in the matrix.

Trade-offs

Pros

  • Simple to understand and implement.

  • Works for any m x n matrix, including square and non-square matrices.

  • Optimal in terms of time complexity, as every element must be visited.

Cons

  • Requires extra space proportional to the size of the matrix. This is unavoidable for non-square matrices where the dimensions change.

Solutions

class Solution {public  int[][] transpose(int[][] matrix) {    int m = matrix.length, n = matrix[0].length;    int[][] ans = new int[n][m];    for (int i = 0; i < n; ++i) {      for (int j = 0; j < m; ++j) {        ans[i][j] = matrix[j][i];      }    }    return ans;  }}

Video walkthrough

Newsletter

One sharp idea, every week

System design and interview prep — short enough to finish.

No spam. Unsubscribe anytime.

Practice

Same difficulty — related problems to reinforce the pattern.