↓Skip to main content
  1. LeetCode/

LeetCode 867: Transpose Matrix

·1 min· ·
LeetCode Easy Array Matrix Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-17

  • Submissions: Runtime Error ×2 → Accepted ×3

Approach
#

Transposing swaps rows and columns (Matrix Template 1): an m × n matrix becomes n × m with res[j][i] = matrix[i][j]. The outer loop runs over the new rows (old columns), the inner over the new columns (old rows). Python’s zip(*matrix) is exactly the transpose, with tuples as rows.

My Attempts
#

The first two swapped the loop ranges: attempt 1 even passed matrix[0] (a list) to range, and attempt 2 used len(matrix[0]) but with inner and outer reversed, so the non-square [[5, 0]] went out of range. A one-line zip(*matrix) passed.

Solution
#

class Solution:
    def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
        m, n = len(matrix), len(matrix[0])
        return [[matrix[i][j] for i in range(m)] for j in range(n)]

Complexity
#

Time O(mn), space O(mn) (output).

Mistakes to Avoid
#

  • The matrix need not be square; size both loops to the new shape.

Interview Explanation
#

Transposing swaps rows and columns, so I build an n × m matrix whose row j, column i holds the original row i, column j. Time O(mn).

Related

LeetCode 566: Reshape the Matrix
·2 mins
LeetCode Easy Array Matrix Simulation
LeetCode 566 note: return the original if the element counts differ; otherwise element k goes to (k // c, k % c)
LeetCode 832: Flipping an Image
·2 mins
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 note: reverse each row and invert its bits, which two pointers can do at once
LeetCode 766: Toeplitz Matrix
·2 mins
LeetCode Easy Array Matrix
LeetCode 766 note: every diagonal is constant exactly when each cell equals its upper-left neighbor
LeetCode 733: Flood Fill
·2 mins
LeetCode Easy Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 733 note: DFS or BFS from the start, recoloring 4-directional cells that share the start’s original color; return immediately if the colors are equal
LeetCode 661: Image Smoother
·2 mins
LeetCode Easy Array Matrix
LeetCode 661 note: each cell becomes the floored average of the existing cells in its 3 × 3 neighborhood, written into a new matrix
LeetCode 463: Island Perimeter
·2 mins
LeetCode Easy Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 463 note: each land cell contributes 4 edges, minus 2 for each land neighbor above or to the left