Diagonal Traverse

Medium

Topics
ArrayMatrixSimulation

Given an m x n matrix, return all its elements in diagonal order.

The diagonals are the groups of cells with the same row + column sum, taken in increasing order of that sum. Consecutive diagonals are traversed in alternating directions: the first upwards (from bottom-left toward top-right), the second downwards, and so on.

Example 1

grid012314562789012
answer124753689
diagonals read upwardsdiagonals read downwards
Cells on one diagonal all share the same row + column sum, and the diagonals come out in increasing order of that sum. Consecutive diagonals are read in opposite directions, starting upwards — the two shades are the two directions, and the answer row is the result.
2D grid — one row per line.
Input:  grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
Explanation: Diagonal 0 is 1; diagonal 1 is read upwards as 2, 4; diagonal 2 downwards as 7, 5, 3; diagonal 3 upwards as 6, 8; diagonal 4 is 9.

Example 2

grid01213401
answer1234
diagonals read upwardsdiagonals read downwards
Input:  grid = [[1,2],[3,4]]
Output: [1,2,3,4]
Explanation: Diagonal 1 reads upwards as 2, 3.

Example 3

grid0123012
answer123
diagonals read upwardsdiagonals read downwards
Input:  grid = [[1,2,3]]
Output: [1,2,3]
Explanation: A single row puts every element on its own diagonal.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10^4
  • 1 <= m * n <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

Walking the matrix cell by cell and turning at the edges means tracking a direction, two kinds of corner and four edge cases, and most wrong answers here come from that bookkeeping rather than from the idea.

The structural fact that removes it: all the cells on one diagonal share the same row + column sum. So the diagonals are not a path to be walked, they are a grouping to be collected — one bucket per sum from 0 to m + n - 2.

Once the cells are grouped, the alternating direction is a detail rather than a traversal problem. Collecting in row-major order fills each bucket top-to-bottom, which is the downward direction; reversing the buckets whose sum is even gives the upward ones. There is no turning and no edge to detect.

Approach

  1. Create a bucket for each possible value of row + column.
  2. Sweep the matrix in row-major order, appending each cell to the bucket for its own sum. Within a bucket the cells now run from the top row downwards.
  3. Reverse every bucket whose index is even, since the first diagonal is read upwards and the directions alternate from there.
  4. Concatenate the buckets in index order.

Walkthrough

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

row+col sums
   0 1 2
   1 2 3
   2 3 4

buckets filled row-major (top row first)
   sum 0: [1]
   sum 1: [2, 4]
   sum 2: [3, 5, 7]
   sum 3: [6, 8]
   sum 4: [9]

reverse the even sums (0, 2, 4)
   sum 0: [1]
   sum 1: [2, 4]
   sum 2: [7, 5, 3]
   sum 3: [6, 8]
   sum 4: [9]

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

Complexity

  • Time — O(m * n): each cell is placed once and read once.
  • Space — O(m * n): the buckets hold every cell. A pointer-walking solution is O(1) beyond the output, which is its one advantage.

Common Pitfalls

  • Reversing the odd diagonals instead of the even ones. Diagonal 0 has a single cell so it looks the same either way, and the error only shows from diagonal 1 onwards.
  • Sizing the bucket list as m + n rather than m + n - 1, which leaves a trailing empty diagonal.
  • Assuming the matrix is square. A single row or column is valid, and so is any rectangle.
  • Walking with a direction flag and forgetting that at the end of an upward run the next move is down or right depending on which edge was hit. This is exactly the bookkeeping the bucket approach avoids.

Full Solution — all languages

class Solution:
    def findDiagonalOrder(self, matrix):
        rows, cols = len(matrix), len(matrix[0])
        buckets = [[] for _ in range(rows + cols - 1)]
        for r in range(rows):
            for c in range(cols):
                buckets[r + c].append(matrix[r][c])
        out = []
        for total, bucket in enumerate(buckets):
            out.extend(reversed(bucket) if total % 2 == 0 else bucket)
        return out
SensAI
Beta
Tap the mic to stop voice mode