Diagonal Traverse
Medium
Topics
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
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.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
Input: grid = [[1,2],[3,4]] Output: [1,2,3,4] Explanation: Diagonal 1 reads upwards as 2, 3.
Example 3
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
- Create a bucket for each possible value of
row + column. - 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.
- Reverse every bucket whose index is even, since the first diagonal is read upwards and the directions alternate from there.
- 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 + nrather thanm + 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 outimport java.util.*;
class Solution {
public java.util.List<Integer> findDiagonalOrder(int[][] matrix) {
int rows = matrix.length, cols = matrix[0].length;
List<List<Integer>> buckets = new ArrayList<>();
for (int i = 0; i < rows + cols - 1; i++) buckets.add(new ArrayList<>());
for (int r = 0; r < rows; r++) for (int c = 0; c < cols; c++) buckets.get(r + c).add(matrix[r][c]);
List<Integer> out = new ArrayList<>();
for (int i = 0; i < buckets.size(); i++) {
List<Integer> bucket = buckets.get(i);
if (i % 2 == 0) {
for (int j = bucket.size() - 1; j >= 0; j--) out.add(bucket.get(j));
} else {
out.addAll(bucket);
}
}
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
int rows = matrix.size(), cols = matrix[0].size();
vector<vector<int>> buckets(rows + cols - 1);
for (int r = 0; r < rows; r++) for (int c = 0; c < cols; c++) buckets[r + c].push_back(matrix[r][c]);
vector<int> out;
for (size_t i = 0; i < buckets.size(); i++) {
if (i % 2 == 0) {
for (int j = (int)buckets[i].size() - 1; j >= 0; j--) out.push_back(buckets[i][j]);
} else {
for (int v : buckets[i]) out.push_back(v);
}
}
return out;
}
};/**
* @param {number[][]} matrix
* @return {number[]}
*/ var findDiagonalOrder = function(matrix) {
const rows = matrix.length, cols = matrix[0].length;
const buckets = Array.from({ length: rows + cols - 1 }, () => []);
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) buckets[r + c].push(matrix[r][c]);
}
let out = [];
for (let i = 0; i < buckets.length; i++) {
out = out.concat(i % 2 === 0 ? buckets[i].slice().reverse() : buckets[i]);
}
return out;
};