Leetcode #498: Diagonal Traverse
In this guide, we solve Leetcode #498 Diagonal Traverse in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order. Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,4,7,5,3,6,8,9] Example 2: Input: mat = [[1,2],[3,4]] Output: [1,2,3,4] Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 104 1 <= m * n <= 104 -105 <= mat[i][j] <= 105
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Matrix, Simulation
Intuition
Grid problems are easiest when you define clear row/column boundaries.
A consistent traversal order prevents off-by-one errors.
Approach
Iterate by rows, columns, or layers depending on the requirement.
Keep bounds updated as the traversal progresses.
Steps:
- Define bounds or directions.
- Visit cells in order.
- Update result and move bounds.
Example
Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
Python Solution
class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
m, n = len(mat), len(mat[0])
ans = []
for k in range(m + n - 1):
t = []
i = 0 if k < n else k - n + 1
j = k if k < n else n - 1
while i < m and j >= 0:
t.append(mat[i][j])
i += 1
j -= 1
if k % 2 == 0:
t = t[::-1]
ans.extend(t)
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.