Problem · Array

Diagonal Matrix Iterator

Learn this problem
MediumMicrosoft logoMicrosoftNEW GRADONSITE INTERVIEW
See Microsoft hiring insights

Problem statement

Given a non-empty rectangular integer matrix matrix, return the sequence produced by a diagonal iterator over all of its elements.

Number diagonals by row + column, starting with diagonal 0 at the top-left cell. The iterator traverses even-numbered diagonals upward and to the right, and odd-numbered diagonals downward and to the left.

The iterator begins at the top-left cell, yields every matrix element exactly once, and is exhausted immediately after yielding the bottom-right cell.

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 Microsoft 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