LeetCode 498: Diagonal Traverse Solution

Master LeetCode problem 498 (Diagonal Traverse), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

498. Diagonal Traverse

Problem Explanation

Explanation

To solve this problem, we can traverse the matrix diagonally in two directions: up-right and down-left. We will switch the direction whenever we reach the boundary of the matrix. By keeping track of the current position and direction, we can construct the diagonal order array.

  1. Initialize variables for the row and column indices, direction flag, and result array.
  2. Loop through the matrix elements while adding elements to the result array in the diagonal order.
  3. Update the row and column indices based on the current direction.
  4. Handle boundary cases to switch the direction.
  5. Return the resulting diagonal order array.

Time Complexity: O(m * n) - where m is the number of rows and n is the number of columns in the matrix.
Space Complexity: O(m * n) - for storing the diagonal order array.

Solution Code

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, direction = 1;
        
        for (int i = 0; i < m * n; i++) {
            result[i] = mat[row][col];
            row -= direction;
            col += direction;
            
            if (row >= m) { row = m - 1; col += 2; direction = -direction; }
            if (col >= n) { col = n - 1; row += 2; direction = -direction; }
            if (row < 0) { row = 0; direction = -direction; }
            if (col < 0) { col = 0; direction = -direction; }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 498 (Diagonal Traverse)?

This page provides optimized solutions for LeetCode problem 498 (Diagonal Traverse) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 498 (Diagonal Traverse)?

The time complexity for LeetCode 498 (Diagonal Traverse) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 498 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 498 in Java, C++, or Python.

Back to LeetCode Solutions