Date: 2026-06-06
Time: 19:31
transpose-matrix/solution.pyThis file solves LeetCode 867 — Transpose Matrix. It owns the single responsibility of flipping a matrix over its main diagonal: rows become columns, columns become rows. Given an m x n input, it produces an n x m output where result[j][i] == matrix[i][j].
Solution.transpose(self, matrix: List[List[int]]) -> List[List[int]] — The sole public method. It takes a 2D list of integers and returns a new 2D list representing the transpose.
m (rows) and n (columns) from the input.j in range(n)), the inner loop over rows (i in range(m)), yielding matrix[i][j] at each position.Single list-comprehension solution — The entire transformation is expressed as one nested comprehension with no intermediate state. This is idiomatic Python for matrix operations where the mapping from input to output indices is a simple permutation.
Loop order encodes the transpose — The key insight is that the outer loop is j (column index of the input) and the inner loop is i (row index of the input). This naturally produces n rows of m elements each, which is exactly the transposed shape. Swapping which index is outer vs. inner is what makes this a transpose rather than a copy.
Imports: typing.List — used only for type annotations.
Imported by: The test_solution.py in this same directory. The large "Imported By" list in the prompt is an artifact of the test harness structure — those are unrelated test files, not actual consumers of this module.
1. m, n = len(matrix), len(matrix[0]) — read dimensions. O(1).
2. The comprehension iterates n * m times, performing one index lookup per iteration. Total work: O(m * n) time, O(m * n) space for the new matrix.
3. Returns the new matrix. The original is not mutated.
len(matrix[0]) will raise IndexError on an empty matrix. LeetCode's constraints guarantee m >= 1 and n >= 1, so this is safe within the problem's domain.n from row 0 and assumes all rows have the same length. Jagged input would silently produce wrong results (or IndexError) rather than being detected.n rows and m columns, which is the defining property of a transpose.None. The function trusts its input conforms to the LeetCode contract. No validation, no try/except. This is appropriate for a competitive-programming solution operating within guaranteed constraints.