Problem · Matrix

Diagonal Traverse (for E4 ;)

Learn this problem
MediumMeta logoMetaFULLTIMEPHONE SCREEN
See Meta hiring insights

Problem statement

LC 498~ The other question was LC 1539~~

Given an m × n matrix mat, return an array of all the elements of the array in a diagonal order.

Function

findDiagonalOrder(mat: int[][]) → int[]

Examples

Example 1

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

Traverse the matrix diagonally as follows:

  1. Start from element 1
  2. Move up-right to reach 2, then down-left to 4
  3. Move up-right to reach 7, then down-right to 3
  4. Continue the pattern to traverse all elements diagonally
The resulting diagonal order is [1,2,4,7,3,5,8,6,9].

Example 2

mat = [[1,2],[3,4]]return = [1,2,3,4]

Traverse the matrix diagonally as follows:

  1. Start from element 1
  2. Move up-right to reach 2, then down-left to 3
  3. Finally, move up-right to reach 4
The resulting diagonal order is [1,2,3,4].

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 10⁴
  • 1 <= m * n <= 10⁴
  • -10⁵ <= mat[i][j] <= 10⁵

More Meta problems

drafts saved locally
public int[] findDiagonalOrder(int[][] mat) {
  // write your code here
}
mat[[1,2,3],[4,5,6],[7,8,9]]
expected[1,2,4,7,3,5,8,6,9]
checking account