Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created August 25, 2025 19:09
Show Gist options
  • Save tatsuyax25/f878d0d9ab125b38fa8fce56e2752f8b to your computer and use it in GitHub Desktop.
Save tatsuyax25/f878d0d9ab125b38fa8fce56e2752f8b to your computer and use it in GitHub Desktop.
Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
/**
* @param {number[][]} mat
* @return {number[]}
*/
var findDiagonalOrder = function(mat) {
// Edge case: empty matrix
if (!mat || mat.length === 0 || mat[0].length === 0) return [];
const m = mat.length; // number of rows
const n = mat[0].length; // number of columns
const result = [];
let row = 0, col = 0;
let directionUp = true; // true = moving up-right, false = down-left
// We need to collect m * n elements
while (result.length < m * n) {
result.push(mat[row][col]);
if (directionUp) {
// Moving up-right
if (col === n - 1) {
// Hit right boundary, move down
row++;
directionUp = false;
} else if (row === 0) {
// Hit top boundary, move right
col++;
directionUp = false;
} else {
// Normal up-right move
row--;
col++;
}
} else {
// Moving down-left
if (row === m - 1) {
// Hit bottom boundary, move right
col++;
directionUp = true;
} else if (col === 0) {
// Hit left boundary, move down
row++;
directionUp = true;
} else {
// Normal down-left move
row++;
col--;
}
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment