From d8b353ca1b9ec7e5bc4299a9099082bb33c47098 Mon Sep 17 00:00:00 2001 From: Prasham Mehta <133197683+PrashamMehta-04@users.noreply.github.com> Date: Tue, 7 Oct 2025 21:46:00 +0530 Subject: [PATCH] Add files via upload MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. Approach: We need to sort the diagonals of a square matrix in two different orders depending on their position: Bottom-left triangle diagonals (including the main diagonal) → non-increasing order Top-right triangle diagonals → non-decreasing order The matrix can be divided into diagonals starting from the first column and diagonals starting from the first row (except the main diagonal). For each diagonal, we: -> Extract all elements -> Sort them in the required order (ascending for top-right, descending for bottom-left) -> Place them back into their original positions Intuition: A diagonal in an n×n matrix is uniquely determined by its starting position either from the first column (for bottom-left diagonals) or from the first row (for top-right diagonals). By sorting each diagonal individually and placing it back, we can achieve the desired matrix arrangement efficiently. --- 3446. Sort Matrix by Diagonals.cpp | 70 ++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 3446. Sort Matrix by Diagonals.cpp diff --git a/3446. Sort Matrix by Diagonals.cpp b/3446. Sort Matrix by Diagonals.cpp new file mode 100644 index 0000000..11ccb7e --- /dev/null +++ b/3446. Sort Matrix by Diagonals.cpp @@ -0,0 +1,70 @@ +class Solution { +public: + vector> sortMatrix(vector>& grid) { + vector> ans; + vector 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> a1; + int r = 1; + for(int k=1;k=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