Skip to content

Conversation

@Subhosjx
Copy link
Contributor

@Subhosjx Subhosjx commented Oct 29, 2025

PR Title Format: 3446. Sort Matrix by Diagonals.cpp

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++)

class Solution {
public:
    vector<vector<int>> sortMatrix(vector<vector<int>>& grid) {
        vector<vector<int>> ans;
        vector<int> t;
        int cnt = 1;
        int j=0;
        for(int i=grid.size()-1;i>=0;i--){
            int p=i;
            while(j < grid.size() && p < grid.size()){
                t.push_back(grid[p][j]);
                p++;
                j++;
            }
            sort(t.begin(), t.end());
            reverse(t.begin(), t.end());
            ans.push_back(t);
            t.clear();
            j=0;
        }
        vector<vector<int>> a1;
        int r = 1;
        for(int k=1;k<grid.size();k++){
            int q = 0;
            int d = r;
            while(q < grid.size() && d < grid.size()){
                t.push_back(grid[q][d]);
                q++;
                d++;
            }
            sort(t.begin(), t.end());
            a1.push_back(t);
            t.clear();
            r++;
        }
        for(int i=0;i<a1.size();i++){
            ans.push_back(a1[i]);
        }
        j = grid.size()-1;
        int p = 0,q=0;
        for(int i=grid.size()-1;i>=0;i--){
            int r = i;
            while(q < ans[p].size()){
                grid[r][j] = ans[p][q];
                q++;
                r++;
                j++;
            } 
            j=0;
            q=0;
            p++;
        }
        q=0;
        j=1;
        r=0;
        for(int i=1;i<grid.size();i++){
            while(q < ans[p].size()){
                grid[r][j] = ans[p][q];
                q++;
                r++;
                j++;
            }
            j=i+1;
            r=0;
            q=0;
            p++;
        }
        return grid;
    }
};

    

Related Issues

#144

By submitting this PR, I confirm that:

  • This is my original work not totally AI generated
  • I have tested the solution thoroughly on leetcode
  • I have maintained proper PR description format
  • This is a meaningful contribution, not spam

Summary by Sourcery

Sort matrix diagonals by extracting each diagonal, sorting bottom-left diagonals in descending order and top-right diagonals in ascending order, and writing values back to the grid.

New Features:

  • Add sortMatrix method to process and sort each diagonal of the matrix
  • Sort diagonals starting from the first column in non-increasing order
  • Sort diagonals starting from the first row in non-decreasing order

@sourcery-ai
Copy link

sourcery-ai bot commented Oct 29, 2025

Reviewer's Guide

This PR introduces a new C++ solution that sorts each diagonal of an n×n matrix by extracting diagonals from the bottom-left and top-right regions into temporary arrays, sorting them in the required order, and then writing the sorted values back into the original grid.

Class diagram for the new Solution class implementing diagonal sorting

classDiagram
class Solution {
  +vector<vector<int>> sortMatrix(vector<vector<int>>& grid)
}

class vector
class vector_vector_int
class vector_int

Solution --> vector_vector_int
Solution --> vector_int
vector_vector_int <|-- vector
vector_int <|-- vector
Loading

Flow diagram for diagonal extraction, sorting, and placement in the matrix

flowchart TD
    A[Start] --> B[Extract bottom-left diagonals]
    B --> C[Sort each bottom-left diagonal in descending order]
    C --> D[Extract top-right diagonals]
    D --> E[Sort each top-right diagonal in ascending order]
    E --> F[Place sorted diagonals back into matrix]
    F --> G[Return updated matrix]
Loading

File-Level Changes

Change Details Files
Add bottom-left diagonal extraction and sorting logic
  • Loop from last row to first row extracting diagonals starting at (i,0)
  • Sort each extracted diagonal in descending (non-increasing) order
  • Push sorted diagonals into the ans container
3446. Sort Matrix by Diagonals.cpp
Add top-right diagonal extraction and sorting logic
  • Loop from second column to last extracting diagonals starting at (0,j)
  • Sort each extracted diagonal in ascending (non-decreasing) order
  • Store sorted diagonals in a1 and append them to ans
3446. Sort Matrix by Diagonals.cpp
Implement grid reconstruction using sorted diagonals
  • Iterate through ans to overwrite bottom-left diagonals in the matrix
  • Continue through ans to overwrite top-right diagonals
  • Manage and reset row/column pointers for each diagonal placement
3446. Sort Matrix by Diagonals.cpp

Possibly linked issues

  • #3446: The PR implements the C++ solution for sorting matrix diagonals as detailed in issue 3446.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Refactor the diagonal extraction and writing logic into a helper function to avoid duplicating the bottom-left and top-right processing loops.
  • Replace single-letter variables like p, q, r, and j with descriptive names such as row and col to make the iteration logic clearer.
  • Instead of collecting all diagonals into ans/a1 then writing back later, consider sorting and writing each diagonal in place to simplify the control flow and reduce indexing errors.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Refactor the diagonal extraction and writing logic into a helper function to avoid duplicating the bottom-left and top-right processing loops.
- Replace single-letter variables like p, q, r, and j with descriptive names such as row and col to make the iteration logic clearer.
- Instead of collecting all diagonals into ans/a1 then writing back later, consider sorting and writing each diagonal in place to simplify the control flow and reduce indexing errors.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@SjxSubham SjxSubham changed the title Implement diagonal sorting for a matrix 3446. Sort Matrix by Diagonals.cpp Oct 29, 2025
@SjxSubham SjxSubham linked an issue Oct 29, 2025 that may be closed by this pull request
4 tasks
@SjxSubham SjxSubham added the hacktoberest-accepted hacktoberfest-accepted label Oct 29, 2025
@SjxSubham SjxSubham merged commit 1089be2 into SjxSubham:main Oct 29, 2025
2 checks passed
@github-actions
Copy link

🎉 Congrats on getting your PR merged in, @Subhosjx! 🙌🏼

Thanks for your contribution every effort helps improve the project.

Looking forward to seeing more from you! 🥳✨

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hacktoberest-accepted hacktoberfest-accepted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3446: Sort Matrix by Diagonals

2 participants