Diagonal Traverse
Simulation Array
Problem
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
For example:
Thought Process
Notice how essentially, we are only going in two directions, up and down. More specifically, going in a up-right pattern and a down-left pattern
When going up, if you hit the top border, you have to go right one element; if you hit the far right border, you have to go down one element. Similarly, when going down, if you hit the bottom border, you have to go right one element; if you hit the far left border, you have to go down one element.
The reason a boolean works better for keeping track of direction compared to a variable (like in Spiral Order Matrix) is because we only need to keep track of two directions compared to four. The boolean allows us to flip between traversing the two directions like a light switch.
Solution
Key Facts
Two cases we need to check for each direction:
When going down if we are in the first column or the last row
When going up if we are in the last column or top row
To keep track of changing directions, we use a boolean variable since there are only two directions we are traversing. All we need to check is if this boolean is true or false to determine the direction we are traversing
Time Complexity
Time:
Space: for the return array
Last updated
Was this helpful?