Good evening! Here's our prompt for today.
Diagonal Matrix Traversal
We are given a matrix with m
rows and n
columns. For example:
SNIPPET
1[
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9]
5]
Our goal is to traverse the matrix diagonally and return the elements in that order.
What does "diagonal" mean? It means we want to go through the matrix diagonally like this:

So we start at the top left, go right, then down and left in a zig-zag.
Key Points
- We are given a 2D matrix with
m
rows andn
columns - We need to traverse it diagonally
- Return the elements in an array in diagonal order
Constraints
m
= number of rows in matrixn
= number of columns in matrix1 <= m, n <= 104
(1 to 10,000)1 <= m * n <= 104
- Matrix values are integers between
-105
and105
So in summary, we need to take a 2D matrix and figure out how to traverse it diagonally, returning the values in that order.
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
41
var assert = require('assert');
​
function find_diagonal_order(matrix) {
//fill in the solution
return matrix
}
​
​
try {
assert.deepEqual(find_diagonal_order([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]), [1, 2, 4, 7, 5, 3, 6, 8, 9]);
​
console.log('PASSED: ' + "find_diagonal_order([[1,2,3],[4,5,6],[7,8,9]]) should return `[1,2,4,7,5,3,6,8,9]`");
} catch (err) {
console.log(err);
}
​
try {
assert.deepEqual(find_diagonal_order([
[1, 2],
[3, 4]
]), [1, 2, 3, 4]);
​
console.log('PASSED: ' + "find_diagonal_order([[1,2],[3,4]]) should return `[1,2,3,4]`");
} catch (err) {
console.log(err);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's how we would solve this problem...
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.