v9.1.1
Menu

Diagonal Traverse

mediumFREEArrays & Matrix OperationsDSA for AI Engineers

Given an m x n matrix, return all elements in diagonal order (alternating up-right and down-left), starting at the top-left element.

Return the elements as a list. The test harness prints them space-separated.

Example

Input
1,2,3
4,5,6
7,8,9
Output
1 2 4 7 5 3 6 8 9
Reasoning
  • The input is a 3×33 \times 3 grid read row by row: 1,2,3 is row 0, 4,5,6 is row 1, 7,8,9 is row 2.
  • An anti-diagonal is a set of cells running from upper-right to lower-left. A 3×33 \times 3 grid has 3+3−1=53 + 3 - 1 = 5 of them, holding {1}\{1\}, {2,4}\{2, 4\}, {3,5,7}\{3, 5, 7\}, {6,8}\{6, 8\} and {9}\{9\}.
  • The first one is just 11, the top-left corner. The second is read moving down-left, so 22 comes before 44.
  • The third is read moving up-right: it starts at the bottom-left 77, passes the centre 55 and ends at the top-right 33.
  • The fourth flips back to down-left (66 then 88), and the last is the corner 99.
  • Joining them gives 1 2 4 7 5 3 6 8 9. Notice that every element appears exactly once, and that the reading direction reverses on each successive diagonal. For a 2×22 \times 2 grid with rows 1,21, 2 and 3,43, 4 the same pattern happens to give 1 2 3 4.

Constraints

  • 1 <= m, n <= 10^4
  • 1 <= m * n <= 10^4

More from DSA for AI Engineers

solution.py

Test results

Sign in to run your code against the test cases.