Opening the reading…
Opening the reading…
MATRIX › MATRIX TRAVERSAL AND SUMMATION
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →A diagonal traversal always changes the row and column by one in opposite directions. During an up-right run, the row decreases while the column increases. During a down-left run, the row increases while the column decreases. Starting at the top-left cell, you keep following that direction until one coordinate leaves the matrix, then begin the next diagonal from the boundary cell that follows it.
The important detail is that the cell which ends a run has already been visited. If the up-right run leaves through the right edge, the next valid start is two rows below the last cell and one column back. If it leaves through the top edge, the next start is one row down. The down-left case is the same idea with rows and columns exchanged.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(mn) | Each cell is appended exactly once, and every inner-loop iteration advances to a new matrix position. The boundary corrections take constant time between runs, so they add at most one constant amount per diagonal and never cause a cell to be processed again. |
| Space | O(1) extra | Only row, column, direction, and a few size variables are used besides the returned array. The returned array contains mn elements and is required output, so it is excluded from the extra-space bound; the bound stays O(1) for every matrix shape. |
#include <vector>
using namespace std;
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
vector<int> result;
result.reserve(m * n);
int row = 0;
int col = 0;
bool up = true;
while (row < m && col < n) {
if (up) {
while (row >= 0 && col < n) {
result.push_back(mat[row][col]);
--row;
++col;
}
if (col == n) {
--col;
row += 2;
} else {
++row;
}
} else {
while (row < m && col >= 0) {
result.push_back(mat[row][col]);
++row;
--col;
}
if (row == m) {
--row;
col += 2;
} else {
++col;
}
}
up = !up;
}
return result;
}
};The inner loop deliberately performs one move beyond the last valid cell. That makes the stopping condition uniform: the loop ends because either row or column is outside the matrix, and the correction code converts that outside position into the first valid position of the next diagonal. reserve does not change the algorithm; it simply allocates space for the known output size once.