Sort the Matrix Diagonally — LeetCode 1329 Python Solution
- Problem
- #1329
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The problem
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2].
Example
- Input
- mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
- Output
- [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
Python solution
class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0])
g = [[] for _ in range(m + n)]
for i, row in enumerate(mat):
for j, x in enumerate(row):
g[m - i + j].append(x)
for e in g:
e.sort(reverse=True)
for i in range(m):
for j in range(n):
mat[i][j] = g[m - i + j].pop()
return matComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n \times \log \min(m, n)) |
| Space | O(m \times n) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1329. Sort the Matrix Diagonally is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1329. Sort the Matrix Diagonally?
- LeetCode 1329. Sort the Matrix Diagonally is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1329. Sort the Matrix Diagonally?
- The Python solution on this page runs in O(m \times n \times \log \min(m, n)).
- What is the space complexity of LeetCode 1329. Sort the Matrix Diagonally?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 1329. Sort the Matrix Diagonally cover?
- LeetCode 1329. Sort the Matrix Diagonally is tagged Array, Matrix and Sorting on LeetCode.