Leetcode 1329: Sort the Matrix Diagonally

grid47
grid47
Exploring patterns and algorithms
Jun 27, 2024 6 min read

You are given a matrix mat of integers with dimensions m x n. A matrix diagonal is a sequence of matrix elements that start from some cell in the topmost row or leftmost column and go diagonally towards the bottom-right corner. Your task is to sort each matrix diagonal in ascending order and return the resulting matrix.
Problem
Approach
Steps
Complexity
Input: The input consists of a 2D integer matrix `mat` of dimensions `m x n`.
Example: For example, given mat = [[5, 9, 3], [8, 6, 1], [7, 4, 2]], the task is to sort each diagonal of this matrix.
Constraints:
• 1 <= m, n <= 100
• 1 <= mat[i][j] <= 100
Output: The output should be the matrix where each diagonal is sorted in ascending order.
Example: For mat = [[5, 9, 3], [8, 6, 1], [7, 4, 2]], the output would be [[1, 3, 2], [4, 5, 1], [7, 6, 9]].
Constraints:
Goal: Sort the elements along each diagonal of the matrix in ascending order while keeping the relative positions of the diagonals unchanged.
Steps:
• 1. Identify all diagonals in the matrix.
• 2. For each diagonal, store the elements and sort them in ascending order.
• 3. Replace the original elements of each diagonal with the sorted values.
• 4. Return the modified matrix.
Goal: The input matrix `mat` will have at least one row and one column, and the matrix values are constrained by the size limits.
Steps:
• 1 <= m, n <= 100
• 1 <= mat[i][j] <= 100
Assumptions:
• The matrix is not empty, and each element is an integer between 1 and 100.
Input: Input: mat = [[5, 9, 3], [8, 6, 1], [7, 4, 2]]
Explanation: The diagonals are [5], [9, 8], [3, 6, 7], [1, 4], and [2]. After sorting each diagonal, we get the matrix [[1, 3, 2], [4, 5, 1], [7, 6, 9]].

Input: Input: mat = [[10, 21, 30], [4, 15, 24], [5, 6, 23]]
Explanation: The diagonals are [10], [21, 4], [30, 15, 5], [24, 6], and [23]. After sorting each diagonal, we get the matrix [[4, 15, 23], [5, 21, 30], [10, 6, 24]].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus