KatInterview

498. Diagonal Traverse

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Direct Simulation

This problem asks us to traverse a 2D matrix in a specific diagonal, zig-zag pattern. A straightforward and space-efficient way to solve this is by simulating the traversal path directly.

Solution

Diagonal Traverse in Python

class Solution:
    def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
        if not mat or not mat[0]:
            return []

        m, n = len(mat), len(mat[0])
        result = [0] * (m * n)
        row, col = 0, 0

        for i in range(m * n):
            result[i] = mat[row][col]

            # The sum of indices (row + col) determines the direction.
            # Even sum: move up-right.
            # Odd sum: move down-left.
            if (row + col) % 2 == 0:  # Moving up-right
                # Check boundaries in order: right, top, then middle.
                if col == n - 1:
                    # Hit the right wall, must go down.
                    row += 1
                elif row == 0:
                    # Hit the top wall, must go right.
                    col += 1
                else:
                    # In the middle, continue up-right.
                    row -= 1
                    col += 1
            else:  # Moving down-left
                # Check boundaries in order: bottom, left, then middle.
                if row == m - 1:
                    # Hit the bottom wall, must go right.
                    col += 1
                elif col == 0:
                    # Hit the left wall, must go down.
                    row += 1
                else:
                    # In the middle, continue down-left.
                    row += 1
                    col -= 1

        return result

Diagonal Traverse in Java

class Solution {
    public int[] findDiagonalOrder(int[][] mat) {
        if (mat == null || mat.length == 0) {
            return new int[0];
        }

        int m = mat.length;
        int n = mat[0].length;
        int[] result = new int[m * n];
        int row = 0, col = 0;

        for (int i = 0; i < m * n; i++) {
            result[i] = mat[row][col];

            // The sum of indices (row + col) determines the direction.
            // Even sum: move up-right.
            // Odd sum: move down-left.
            if ((row + col) % 2 == 0) { // Moving up-right
                // Check boundaries in order: right, top, then middle.
                if (col == n - 1) {
                    // Hit the right wall, must go down.
                    row++;
                } else if (row == 0) {
                    // Hit the top wall, must go right.
                    col++;
                } else {
                    // In the middle, continue up-right.
                    row--;
                    col++;
                }
            } else { // Moving down-left
                // Check boundaries in order: bottom, left, then middle.
                if (row == m - 1) {
                    // Hit the bottom wall, must go right.
                    col++;
                } else if (col == 0) {
                    // Hit the left wall, must go down.
                    row++;
                } else {
                    // In the middle, continue down-left.
                    row++;
                    col--;
                }
            }
        }

        return result;
    }
}

Diagonal Traverse in C++

class Solution {
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
        if (mat.empty() || mat[0].empty()) {
            return {};
        }

        int m = mat.size();
        int n = mat[0].size();
        vector<int> result(m * n);
        int row = 0, col = 0;

        for (int i = 0; i < m * n; ++i) {
            result[i] = mat[row][col];

            // The sum of indices (row + col) determines the direction.
            // Even sum: move up-right.
            // Odd sum: move down-left.
            if ((row + col) % 2 == 0) { // Moving up-right
                // Check boundaries in order: right, top, then middle.
                if (col == n - 1) {
                    // Hit the right wall, must go down.
                    row++;
                } else if (row == 0) {
                    // Hit the top wall, must go right.
                    col++;
                } else {
                    // In the middle, continue up-right.
                    row--;
                    col++;
                }
            } else { // Moving down-left
                // Check boundaries in order: bottom, left, then middle.
                if (row == m - 1) {
                    // Hit the bottom wall, must go right.
                    col++;
                } else if (col == 0) {
                    // Hit the left wall, must go down.
                    row++;
                } else {
                    // In the middle, continue down-left.
                    row++;
                    col--;
                }
            }
        }

        return result;
    }
};

Diagonal Traverse in TypeScript

function findDiagonalOrder(mat: number[][]): number[] {
    if (mat === null || mat.length === 0) {
        return [];
    }

    const m = mat.length;
    const n = mat[0].length;
    const result = new Array(m * n);
    let row = 0, col = 0;

    for (let i = 0; i < m * n; i++) {
        result[i] = mat[row][col];

        // The sum of indices (row + col) determines the direction.
        // Even sum: move up-right.
        // Odd sum: move down-left.
        if ((row + col) % 2 === 0) { // Moving up-right
            // Check boundaries in order: right, top, then middle.
            if (col === n - 1) {
                // Hit the right wall, must go down.
                row++;
            } else if (row === 0) {
                // Hit the top wall, must go right.
                col++;
            } else {
                // In the middle, continue up-right.
                row--;
                col++;
            }
        } else { // Moving down-left
            // Check boundaries in order: bottom, left, then middle.
            if (row === m - 1) {
                // Hit the bottom wall, must go right.
                col++;
            } else if (col === 0) {
                // Hit the left wall, must go down.
                row++;
            } else {
                // In the middle, continue down-left.
                row++;
                col--;
            }
        }
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.