AlgoDaily

Diagonal Traverse

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Question

Diagonal Matrix Traversal

We are given a matrix with m rows and n columns. For example:

[
  [1, 2, 3],
  [4, 5, 6], 
  [7, 8, 9]
]  

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:

Diagonal traversal visualization

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 and n columns
  • We need to traverse it diagonally
  • Return the elements in an array in diagonal order
Constraints
  • m = number of rows in matrix
  • n = number of columns in matrix
  • 1 <= m, n <= 104 (1 to 10,000)
  • 1 <= m * n <= 104
  • Matrix values are integers between -105 and 105

So in summary, we need to take a 2D matrix and figure out how to traverse it diagonally, returning the values in that order.

CONTINUE WITH ALGODAILY PREMIUM

Keep going with the complete tutorial.

Unlock the remaining explanations and exercises, alongside the full learning library.

Explore Premium →
Open interactive view →