Skip to content

Commit 8953bee

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 3346
1 parent ab1ebe1 commit 8953bee

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,7 @@
297297
- [3136 Valid Word](https://leetcode.com/problems/valid-word/description/)
298298
- [3202 Find the Maximum Length of Valid Subsequence II](https://leetcode.com/problems/find-the-maximum-length-of-valid-subsequence-ii/description/)
299299
- [3392 Count Subarrays of Length Three With a Condition](https://leetcode.com/problems/count-subarrays-of-length-three-with-a-condition/description/)
300+
- [3446 Sort Matrix by Diagonals](https://leetcode.com/problems/sort-matrix-by-diagonals/description/)
300301

301302
## Development 🔧
302303

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def sortMatrix(self, grid: List[List[int]]) -> List[List[int]]:
8+
"""
9+
You are given an n x n square matrix of integers grid. Return the matrix such
10+
that:
11+
- The diagonals in the bottom-left triangle (including the middle diagonal) are
12+
sorted in non-increasing order.
13+
- The diagonals in the top-right triangle are sorted in non-decreasing order.
14+
"""
15+
# Collect diagonals
16+
diag = {}
17+
for i in range(len(grid)):
18+
for j in range(len(grid[0])):
19+
key = i - j
20+
if key not in diag:
21+
diag[key] = []
22+
diag[key].append(grid[i][j])
23+
24+
# Sort in decreasing / increasing order for each diagonal
25+
diag = dict(
26+
zip(
27+
diag.keys(),
28+
map(lambda key: sorted(diag[key], reverse=(key >= 0)), diag.keys()),
29+
strict=False,
30+
)
31+
)
32+
33+
# Apply the sorted diagonals to the result matrix
34+
result = [[0 for _ in range(len(grid[0]))] for _ in range(len(grid))]
35+
for i in range(len(grid)):
36+
for j in range(len(grid[0])):
37+
key = i - j
38+
result[i][j] = diag[key].pop(0)
39+
40+
return result
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._3446_sort_matrix_by_diagonals import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["grid", "expected"],
10+
argvalues=[
11+
([[1, 7, 3], [9, 8, 2], [4, 5, 6]], [[8, 2, 3], [9, 6, 7], [4, 5, 1]]),
12+
([[0, 1], [1, 2]], [[2, 1], [1, 0]]),
13+
([[1]], [[1]]),
14+
],
15+
)
16+
def test_func(grid: List[List[int]], expected: List[List[int]]):
17+
"""Tests the solution of a LeetCode problem."""
18+
sorted_grid = Solution().sortMatrix(grid)
19+
assert sorted_grid == expected

0 commit comments

Comments
 (0)