LeetCode 3446: Sort Matrix by Diagonals Solution
Master LeetCode problem 3446 (Sort Matrix by Diagonals), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To solve this problem, we can iterate through each diagonal of the matrix and sort the elements in each diagonal according to the specified order. We can start from the bottom-left corner diagonals, sort them in non-increasing order, and then move to the top-right corner diagonals, sorting them in non-decreasing order.
- We can represent each diagonal as a list of elements.
- Sort the diagonals in the bottom-left triangle (including the middle diagonal) in non-increasing order.
- Sort the diagonals in the top-right triangle in non-decreasing order.
- Update the matrix with the sorted elements in each diagonal.
The time complexity of this approach is O(n^2 log n) where n is the size of the grid (n x n matrix), and the space complexity is O(n) for storing the diagonals.
:
Solution Code
class Solution {
public int[][] diagonalSort(int[][] grid) {
int n = grid.length;
List<List<Integer>> diagonals = new ArrayList<>();
for (int k = 1 - n; k < n; k++) {
List<Integer> diagonal = new ArrayList<>();
for (int i = 0; i < n; i++) {
int j = i + k;
if(j >= 0 && j < n) {
diagonal.add(grid[i][j]);
}
}
diagonal.sort((a, b) -> b - a); // Sort in non-increasing order
diagonals.add(diagonal);
}
for (int k = 1; k < n; k++) {
List<Integer> diagonal = new ArrayList<>();
for (int i = 0; i < n; i++) {
int j = i + k;
if(j >= 0 && j < n) {
diagonal.add(grid[i][j]);
}
}
diagonal.sort((a, b) -> a - b); // Sort in non-decreasing order
int idx = 0;
for (int i = 0; i < n; i++) {
int j = i + k;
if(j >= 0 && j < n) {
grid[i][j] = diagonal.get(idx++);
}
}
}
return grid;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3446 (Sort Matrix by Diagonals)?
This page provides optimized solutions for LeetCode problem 3446 (Sort Matrix by Diagonals) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3446 (Sort Matrix by Diagonals)?
The time complexity for LeetCode 3446 (Sort Matrix by Diagonals) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3446 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3446 in Java, C++, or Python.