MediumNo. 0498

Diagonal Traverse — LeetCode 498 Python Solution

Topics
Array, Matrix, Simulation
Reading time
3 min

The problem

Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.

Example

Input
mat = [[1,2,3],[4,5,6],[7,8,9]]
Output
[1,2,4,7,5,3,6,8,9]

Python solution

PythonSolution
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

Time
O(m × n)
Space · auxiliary
O(1)

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 498. Diagonal Traverse is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
1424Diagonal Traverse IIMedium
0054Spiral MatrixMedium
0059Spiral Matrix IIMedium
0289Game of LifeMedium
0566Reshape the MatrixEasy
0867Transpose MatrixEasy

Frequently asked questions

How hard is LeetCode 498. Diagonal Traverse?

LeetCode 498. Diagonal Traverse is rated Medium on LeetCode.

What is the time complexity of LeetCode 498. Diagonal Traverse?

The Python solution on this page runs in O(m × n).

What is the space complexity of LeetCode 498. Diagonal Traverse?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 498. Diagonal Traverse cover?

LeetCode 498. Diagonal Traverse is tagged Array, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.