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.lengthn == mat[i].length1 <= m, n <= 1041 <= m * n <= 104-105 <= mat[i][j] <= 105This approach involves a direct simulation of the diagonal traversal. We use two variables, i and j, to represent the current position in the matrix, and a boolean direction to indicate whether we are moving upwards or downwards diagonally. The process toggles the direction once the boundaries of the matrix are reached, ensuring that the entire matrix is traversed correctly in a zig-zag order.
This C solution simulates diagonal traversal by using a loop that runs until all elements in mat are processed. By switching the direction based on boundary conditions, the code alternates between moving upwards and downwards along diagonals. The final result is stored in an array which is returned.
C++
Java
Python
C#
JavaScript
Time Complexity: O(m * n) as each element is processed once.
Space Complexity: O(m * n) needed for the output array.
This approach leverages a hash map (or dictionary) to collect elements that belong to the same diagonal. The sum of the row and column indices i + j serves as the key, grouping all elements located on the same diagonal. After populating the hash map, we extract and append these elements to the result array, reversing them as needed to maintain the diagonal order.
This C implementation collects elements into arrays stored for each diagonal sum i + j using a dynamic allocation system. After filling these arrays, it extracts and appropriately reverses elements for diagonal order.
C++
Java
Python
C#
JavaScript
Time Complexity: O(m * n), visits each element once.
Space Complexity: O(m * n), required for temporary storage for diagonals.
| Approach | Complexity |
|---|---|
| Approach 1: Direct Simulation | Time Complexity: O(m * n) as each element is processed once. |
| Approach 2: Hash Map of Diagonals | Time Complexity: O(m * n), visits each element once. |
Diagonal Traverse | Live Coding with Explanation | Leetcode - 498 • Algorithms Made Easy • 48,928 views views
Watch 9 more video solutions →Practice Diagonal Traverse with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor