2025-08-25 Daily Challenge

Today I have done leetcode's August LeetCoding Challenge with cpp.

August LeetCoding Challenge 25

Description

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

class Solution {
public:
  vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
    int rows = mat.size();
    int cols = mat.front().size();
    int row = 0;
    int col = 0;
    int direction = 1;
    vector<int> answer;
    while(row < rows && col < cols) {
      // cout << row << ' ' <<col << " -> ";
      answer.push_back(mat[row][col]);
      row -= direction;
      col += direction;
      // cout << row << ' ' <<col << endl;
      direction = -direction;
      if(col == cols) {
        row += 2;
        col -= 1;
      } else if(row == rows) {
        col += 2;
        row -= 1;
      } else if(row < 0) {
        row = 0;
      } else if(col < 0) {
        col = 0;
      } else {
        direction = -direction;
      }
    }
    return answer;
  }
};

// Accepted
// 32/32 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 83.49 % of cpp submissions (22.6 MB)