3446. Sort Matrix by Diagonals.cpp #143
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Intuition
The problem requires sorting matrix diagonals differently based on their position:
Bottom-left triangle (including the main diagonal) → sort in non-increasing order
Top-right triangle → sort in non-decreasing order
Each diagonal can be uniquely identified by its starting position: either from the first column (bottom-left) or from the first row (top-right). Once we know the starting point of a diagonal, we can extract all its elements, sort them according to the required order, and place them back.
By processing one diagonal at a time, we ensure that sorting is localized and does not interfere with other diagonals. This approach leverages the small constraint on 𝑛 ≤ 10 to keep sorting simple and efficient.
Approach
Identify diagonals:
Bottom-left diagonals start from the first column (rows from n-1 to 0).
Top-right diagonals start from the first row (columns from 1 to n-1).
Extract elements of each diagonal into a temporary array.
Sort the diagonal:
Bottom-left → descending order (non-increasing)
Top-right → ascending order (non-decreasing)
Place elements back into the matrix along the same diagonal path.
Repeat for all diagonals until the entire matrix is updated.
Return the updated matrix.
Code Solution (C++)
By submitting this PR, I confirm that: