{x}
blog image

Diagonal Traverse

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

 

Example 1:

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

Example 2:

Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]

 

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • -105 <= mat[i][j] <= 105

Solution Explanation for Diagonal Traverse

The problem asks to traverse a matrix diagonally and return a 1D array containing the elements in the order they were visited.

Approach

The solution iterates through diagonals of the matrix. Each diagonal is processed individually. The direction of traversal alternates between top-right to bottom-left and bottom-left to top-right.

Algorithm:

  1. Iteration over Diagonals: The outer loop iterates from k = 0 to m + n - 2, where m and n are the number of rows and columns respectively. k represents the diagonal number.

  2. Diagonal Traversal: The inner loop traverses a single diagonal. The starting coordinates (i, j) are determined based on k.

    • If k < n, the diagonal starts at (0, k).
    • Otherwise, it starts at (k - n + 1, n - 1).
  3. Direction: The traversal direction is determined by k % 2.

    • If k is even, traverse from top-right to bottom-left.
    • If k is odd, traverse from bottom-left to top-right.
  4. Appending to Result: The elements encountered during the traversal are appended to a temporary list (t).

  5. Reversal (if needed): If k is even, the temporary list t is reversed before being appended to the final result ans. This ensures the correct order.

Time and Space Complexity Analysis

Time Complexity: O(m*n) - Each element in the matrix is visited exactly once.

Space Complexity: O(m*n) in the worst case, because the resultant array can have the size equal to the number of elements in the matrix. If we consider the space used by the temporary list t, its maximum size is min(m, n), which means in the worst case the space complexity could be considered O(min(m,n)) depending on the implementation. However, the dominant factor in space complexity is the output array ans.

Code Explanation (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] # Reverse if k is even
            ans.extend(t)
        return ans
 

The Python code directly implements the algorithm described above. The if k % 2 == 0: condition handles the reversal based on the diagonal number. ans.extend(t) efficiently adds all elements from t to ans.

The other language implementations follow a similar logic, adapting syntax and data structures as needed for each language. The core algorithm remains the same.