LeetCode 498: Diagonal Traverse

ArrayMatrixSimulation

Problem Description

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.

Solutions

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;
    }
}

Loading editor...