3446. Sort Matrix by Diagonals LeetCode Solution

In this guide, you will get 3446. Sort Matrix by Diagonals LeetCode Solution with the best time and space complexity. The solution to Sort Matrix by Diagonals problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Sort Matrix by Diagonals solution in C++
  4. Sort Matrix by Diagonals solution in Java
  5. Sort Matrix by Diagonals solution in Python
  6. Additional Resources
3446. Sort Matrix by Diagonals LeetCode Solution image

Problem Statement of Sort Matrix by Diagonals

You are given an n x n square matrix of integers grid. Return the matrix such that:

The diagonals in the bottom-left triangle (including the middle diagonal) are sorted in non-increasing order.
The diagonals in the top-right triangle are sorted in non-decreasing order.

Example 1:

Input: grid = [[1,7,3],[9,8,2],[4,5,6]]
Output: [[8,2,3],[9,6,7],[4,5,1]]
Explanation:

The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:

[1, 8, 6] becomes [8, 6, 1].
[9, 5] and [4] remain unchanged.

The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:

[7, 2] becomes [2, 7].
[3] remains unchanged.

Example 2:

Input: grid = [[0,1],[1,2]]
Output: [[2,1],[1,0]]
Explanation:

The diagonals with a black arrow must be non-increasing, so [0, 2] is changed to [2, 0]. The other diagonals are already in the correct order.

Example 3:

Input: grid = [[1]]
Output: [[1]]
Explanation:
Diagonals with exactly one element are already in order, so no changes are needed.

See also  841. Keys and Rooms LeetCode Solution

Constraints:

grid.length == grid[i].length == n
1 <= n <= 10
-105 <= grid[i][j] <= 105

Complexity Analysis

  • Time Complexity: O(n^2)
  • Space Complexity: O(n^2)

3446. Sort Matrix by Diagonals LeetCode Solution in C++

class Solution {
 public:
  vector<vector<int>> sortMatrix(vector<vector<int>>& grid) {
    const int n = grid.size();
    vector<vector<int>> ans(n, vector<int>(n));
    vector<vector<int>> diag(2 * n + 1);

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j)
        diag[i - j + n].push_back(grid[i][j]);

    for (int i = 0; i < 2 * n + 1; ++i)
      if (i < n)
        ranges::sort(diag[i], greater<int>());
      else
        ranges::sort(diag[i]);

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j)
        ans[i][j] = diag[i - j + n].back(), diag[i - j + n].pop_back();

    return ans;
  }
};
/* code provided by PROGIEZ */

3446. Sort Matrix by Diagonals LeetCode Solution in Java

class Solution {
  public int[][] sortMatrix(int[][] grid) {
    final int n = grid.length;
    int[][] ans = new int[n][n];
    Map<Integer, List<Integer>> diag = new HashMap<>();

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j) {
        final int key = i - j;
        diag.putIfAbsent(key, new ArrayList<>());
        diag.get(key).add(grid[i][j]);
      }

    for (Map.Entry<Integer, List<Integer>> entry : diag.entrySet()) {
      List<Integer> values = entry.getValue();
      if (entry.getKey() < 0)
        Collections.sort(values, Collections.reverseOrder());
      else
        Collections.sort(values);
    }

    for (int i = 0; i < n; i++)
      for (int j = 0; j < n; j++) {
        final int key = i - j;
        ans[i][j] = diag.get(key).remove(diag.get(key).size() - 1);
      }

    return ans;
  }
}
// code provided by PROGIEZ

3446. Sort Matrix by Diagonals LeetCode Solution in Python

class Solution:
  def sortMatrix(self, grid: list[list[int]]) -> list[list[int]]:
    n = len(grid)
    ans = [[0] * n for _ in range(n)]
    diag = collections.defaultdict(list)

    for i, row in enumerate(grid):
      for j, num in enumerate(row):
        diag[i - j].append(num)

    for key in diag:
      diag[key].sort(reverse=key < 0)

    for i in range(n):
      for j in range(n):
        ans[i][j] = diag[i - j].pop()

    return ans
# code by PROGIEZ

Additional Resources

See also  3288. Length of the Longest Increasing Path LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.