LeetCode 1329: Sort the Matrix Diagonally Solution
Master LeetCode problem 1329 (Sort the Matrix Diagonally), 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 sort each diagonal in the matrix, we can iterate through each diagonal and sort the elements in it. We can use a hashmap to store elements of each diagonal based on their diagonal index. After storing all elements, we can sort the elements in each diagonal and put them back in the matrix.
- Initialize a hashmap to store elements based on their diagonal index.
- Iterate through each element in the matrix and store it in the hashmap based on its diagonal index.
- Sort the elements in each diagonal.
- Put the sorted elements back in the matrix.
Time complexity: O(mnlog(min(m,n)))
Space complexity: O(m*n)
Solution Code
class Solution {
public int[][] diagonalSort(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
Map<Integer, PriorityQueue<Integer>> map = new HashMap<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int diagonalIndex = i - j;
map.putIfAbsent(diagonalIndex, new PriorityQueue<>());
map.get(diagonalIndex).add(mat[i][j]);
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int diagonalIndex = i - j;
mat[i][j] = map.get(diagonalIndex).poll();
}
}
return mat;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1329 (Sort the Matrix Diagonally)?
This page provides optimized solutions for LeetCode problem 1329 (Sort the Matrix Diagonally) 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 1329 (Sort the Matrix Diagonally)?
The time complexity for LeetCode 1329 (Sort the Matrix Diagonally) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1329 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1329 in Java, C++, or Python.