Diagonal Traverse — LeetCode 498 Python Solution

MediumArrayMatrixSimulation
Problem
#498
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

Python
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

MeasureComplexity
TimeO(m \times n)
SpaceO(1) auxiliary

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

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 \times 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.

Get Stealth Interview