← Questions

Diagonal traversal of a matrix

0
MetaCodingLast asked Feb 2026

A coding interview question asked in Meta's AI-enabled coding round, last asked Feb 2026. It tests matrices and simulation.

Given an m x n matrix, return its elements diagonal by diagonal. Cells on the same diagonal share the same row + col. Start with the diagonal holding cell (0, 0). Read the first diagonal going up and to the right, the next going down and to the left, and keep alternating.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • find_diagonal_order(matrix: list[list[int]]) -> list[int] — an empty matrix returns [].

Example

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

[[1, 2],
 [3, 4],
 [5, 6]]             ->  [1, 2, 3, 5, 4, 6]

In the first matrix the diagonals are 1, then 2, 4 (read down-left), then 7, 5, 3 (read up-right), then 6, 8, then 9.

Constraints

  • 0 <= m, n <= 200; all rows have the same length.

Clarifying questions

  • Which direction does the first diagonal go?
  • Can the matrix be empty or have a single row or column?
  • Is the matrix always rectangular?

What a strong answer covers

  • For each diagonal index d from 0 to m + n - 2, compute where the diagonal starts depending on whether d is even (going up) or odd (going down), clamped to the matrix bounds.
  • An alternative: group cells by row + col, then reverse every other group. Simpler, but O(m * n) extra space.
  • O(m * n) time and O(1) extra space beyond the output for the direct walk.
  • Tests: a single row, a single column, a 1 x 1 matrix, wide and tall rectangles, an empty matrix.

Follow-ups

  • Every diagonal is read in the same direction (bottom-left to top-right), and rows may have different lengths. What changes?
  • Read anti-diagonals (row - col constant) instead.
  • Produce the order lazily as an iterator.

Where it's asked

  • Meta · AI-enabled coding · Last asked Feb 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

matrices · simulation

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding