Problem · Array

Diagonal Traverse

Learn this problem
MediumHive AI logoHive AIFULLTIMEPHONE SCREEN

Problem statement

Given a non-empty rectangular integer matrix matrix, return all of its elements in diagonal order.

Number diagonals by row + column, starting with diagonal 0 at the top-left cell. Traverse even-numbered diagonals upward and to the right. Traverse odd-numbered diagonals downward and to the left. Continue until every matrix element has been returned exactly once.

Function

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

Examples

Example 1

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

The diagonals are visited as [1], [2,4], [7,5,3], [6,8], and [9].

Example 2

matrix = [[1,2,3],[4,5,6]]return = [1,2,4,5,3,6]

The traversal alternates direction across the four diagonals of the rectangular matrix.

More Hive AI problems

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