#867

Transpose Matrix

Easy
ArrayMatrixSimulationArrayMatrix
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n)
O(m * n)
Space
O(m * n)
O(m * n)
💡

Intuition

Time O(m * n)Space O(m * n)

The optimal approach leverages the properties of the transpose operation and can be implemented efficiently using a single loop with in-place swapping when modifying the original matrix. However, since we need a new matrix, we will still create a new one but with a clear understanding of the dimensions.

⚙️

Algorithm

2 steps
  1. 1Step 1: Create a new matrix with dimensions swapped (n x m).
  2. 2Step 2: Use a single loop to fill in the new matrix by accessing elements from the original matrix.
solution.py7 lines
1def transpose(matrix):
2    m, n = len(matrix), len(matrix[0])
3    transposed = [[0] * m for _ in range(n)]
4    for i in range(m):
5        for j in range(n):
6            transposed[j][i] = matrix[i][j]
7    return transposed

Complexity note: The time complexity remains O(m * n) as we still need to visit each element. The space complexity is also O(m * n) due to the new matrix.

  • 1Understanding the concept of transposing a matrix is crucial.
  • 2Recognizing that the new matrix dimensions are swapped helps in implementation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.