Diagonal Traverse

Given an `m x n` matrix `mat`, return all of its elements in diagonal order: start at the top-left, walk up and to the right along the first diagonal, then down and to the left along the next, and keep alternating direction until the bottom-right cell.

30:00

Diagonal Traverse
medium
Free written solution
Topics
Companies

Given an m x n matrix mat, return all of its elements in diagonal order: start at the top-left, walk up and to the right along the first diagonal, then down and to the left along the next, and keep alternating direction until the bottom-right cell.

Example 1:
Input: {"mat":[[1,2,3],[4,5,6],[7,8,9]]}
Output: [1,2,4,7,5,3,6,8,9]
Constraints:
  • m==mat.lengthm == \text{mat.length}

  • n==mat[i].lengthn == \text{mat}[i].\text{length}

  • 1≤m,n≤1041 \leq m, n \leq 10^4

  • 1≤m⋅n≤1041 \leq m \cdot n \leq 10^4

  • −105≤mat[i][j]≤105-10^5 \leq \text{mat}[i][j] \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"mat":[[1,2,3],[4,5,6],[7,8,9]]}

Cells on one diagonal share r + c = d. There are 5 diagonals (d = 0 to 4); even ones go up-right, odd ones go down-left.

d = r + c = -

direction -

1
2
3
4
5
6
7
8
9

result (0 of 9)

[]

Variables
VariableValue
m3
n3
DepthFunction Call
Stack empty
0/15