867. Transpose Matrix - Explanation

Problem Link

Description

You are 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 = [
    [2,1],
    [-1,3]
]

Output: [
    [2,-1],
    [1,3]
]

Example 2:

Input: [
    [1,0,5],
    [2,4,3]
]

Output: [
    [1,2],
    [0,4],
    [5,3]
]

Constraints:

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

Company Tags

Please upgrade to NeetCode Pro to view company tags.



1. Iteration - I

class Solution:
    def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
        ROWS, COLS = len(matrix), len(matrix[0])
        res = [[0] * ROWS for _ in range(COLS)]

        for r in range(ROWS):
            for c in range(COLS):
                res[c][r] = matrix[r][c]

        return res

Time & Space Complexity

  • Time complexity: O(nm)O(n * m)
  • Space complexity: O(nm)O(n * m) for the output array.

Where nn is the number of rows and mm is the number of columns in the matrix.


2. Iteration - II

class Solution:
    def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
        ROWS, COLS = len(matrix), len(matrix[0])

        if ROWS == COLS:
            for r in range(ROWS):
                for c in range(r):
                    matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]

            return matrix

        res = [[0] * ROWS for _ in range(COLS)]

        for r in range(ROWS):
            for c in range(COLS):
                res[c][r] = matrix[r][c]

        return res

Time & Space Complexity

  • Time complexity: O(nm)O(n * m)
  • Space complexity: O(nm)O(n * m)

Where nn is the number of rows and mm is the number of columns in the matrix.