Skip to main content
Back to problems
#498
Medium Algorithms

Diagonal traverse

Array Matrix Simulation
67.0% acceptance
Jan 13, 2026
4303
785
Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_diagonal_order(mat: Vec<Vec<i32>>) -> Vec<i32> {
    let m = mat.len();
    let n = mat[0].len();
    let mut result = Vec::with_capacity(m * n);
    let mut row = 0;
    let mut col = 0;
    let mut going_up = true;
    
    for _ in 0..m * n {
      result.push(mat[row][col]);
      
      if going_up {
        if col == n - 1 {
          row += 1;
          going_up = false;
        } else if row == 0 {
          col += 1;
          going_up = false;
        } else {
          row -= 1;
          col += 1;
        }
      } else {
        if row == m - 1 {
          col += 1;
          going_up = true;
        } else if col == 0 {
          row += 1;
          going_up = true;
        } else {
          row += 1;
          col -= 1;
        }
      }
    }
    
    result
  }
}