Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created August 28, 2025 16:28
Show Gist options
  • Save tatsuyax25/23ea548aa35e3b5a6d4292f2198ecc5d to your computer and use it in GitHub Desktop.
Save tatsuyax25/23ea548aa35e3b5a6d4292f2198ecc5d to your computer and use it in GitHub Desktop.
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 n
/**
* @param {number[][]} grid
* @return {number[][]}
*/
var sortMatrix = function(grid) {
const n = grid.length;
// Helper to extract a matrix starting at (row, col)
function getMatrix(row, col) {
const matrix = [];
while (row < n && col < n) {
matrix.push(grid[row][col]);
row++;
col++;
}
return matrix;
}
// Helper to write a sorted matrix back into the grid
function setMatrix(row, col, sorted) {
let i = 0;
while (row < n && col < n) {
grid[row][col] = sorted[i];
row++;
col++;
i++;
}
}
// Bottom-left triangle (including main matrix)
for (let row = 0; row < n; row++) {
const matrix = getMatrix(row, 0);
matrix.sort((a, b) => b - a); // Descending
setMatrix(row, 0, matrix);
}
// Top-right triangle (excluding main matrix)
for (let col = 1; col < n; col++) {
const matrix = getMatrix(0, col);
matrix.sort((a, b) => a - b); // Ascending
setMatrix(0, col, matrix);
}
return grid;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment