498. Diagonal Traverse - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Problem Statement

Given an m x n matrix, return an array of all the elements of the matrix in a diagonal order. The diagonal order means that you traverse the matrix in a zigzag pattern along its diagonals. More precisely, starting from the top-left element, you alternate between moving upward (diagonally up-right) and downward (diagonally down-left) until all elements are traversed.

Example 1

Input:

matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

Output:

[1, 2, 4, 7, 5, 3, 6, 8, 9]

Explanation:

  • Diagonal 0: Contains element [1].
  • Diagonal 1: Contains elements [2, 4] → traversed upward so order becomes [2, 4].
  • Diagonal 2: Contains elements [7, 5, 3] → traversed downward so order remains [7, 5, 3].
  • Diagonal 3: Contains elements [6, 8] → traversed upward so order becomes [6, 8].
  • Diagonal 4: Contains element [9].

When all diagonals are combined in order, we get [1, 2, 4, 7, 5, 3, 6, 8, 9].

Example 2

Input:

matrix = [
  [1, 2],
  [3, 4]
]

Output:

[1, 2, 3, 4]

Explanation:

  • Diagonals: [1], [2, 3], [4].
    Since the second diagonal is traversed upward, it becomes [2, 3].
    Combining all gives [1, 2, 3, 4].

Constraints

  • 1 ≤ matrix.length, matrix[0].length ≤ 10⁴
  • The total number of elements of the matrix will not exceed 10⁴.
  • The matrix elements can be any integers.

Hints

  1. Zigzag Traversal:
    Notice that you alternate the direction of traversal on each diagonal. One diagonal is read from bottom to top (upward) and the next from top to bottom (downward).

  2. Index Sum Grouping:
    Elements on the same diagonal share the same sum of indices (i + j). This property can be used to group elements and then reverse the order of every alternate diagonal.

  3. Boundary Conditions:
    When simulating the diagonal traversal, carefully handle the matrix boundaries (i.e. when you reach the first row or the last column while moving upward, or when you reach the last row or the first column while moving downward).

Approaches

Approach 1: Simulation with Direction Toggling

Idea:
Traverse the matrix by simulating the diagonal movement. Use two variables for the current row and column and a direction flag (upward or downward). At each step, update the position accordingly. When you hit a boundary, change direction and adjust the row/column indices.

Steps:

  1. Initialize row, column, and a boolean flag (for upward direction).

  2. While within bounds, add the current element to the result.

  3. Depending on the current direction:

    • Upward: Move up-right (row–1, col+1).
    • Downward: Move down-left (row+1, col–1).
  4. When hitting a boundary, update row and col to the next valid start position and flip the direction.

Pros:

  • Traverses the matrix in a single pass.
  • Intuitive simulation of the movement.

Cons:

  • Requires careful handling of boundary conditions.

Approach 2: Grouping by Diagonals Using Index Sum

Idea:
Every element at position (i, j) lies on the diagonal identified by the sum d = i + j. Group all elements by their diagonal index. For diagonals with an even index (or based on the traversal order), reverse the order of elements.

Steps:

  1. Iterate over all elements and group them in a hash map (or list) using key = i + j.
  2. For each diagonal group:
    • If the diagonal index is even, reverse the group.
  3. Concatenate all groups in order of increasing diagonal index.

Pros:

  • Cleaner implementation using grouping.
  • Easy to understand the relation using i+j.

Cons:

  • Requires extra space to hold the groups.
  • Two passes over the matrix (one for grouping, one for concatenation).

Step-by-Step Walkthrough (Simulation Approach)

Consider the matrix:

[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
  1. Initialization:

    • Set row = 0, col = 0, directionUp = true.
    • Result list starts as empty.
  2. Traverse:

    • Step 1: (0, 0): Add 1.
      Next move (upward): Attempt (–1, 1) → Out of bounds.
      Since moving upward and row becomes -1, move right to (0, 1) and flip direction.

    • Step 2: (0, 1): Add 2.
      Now direction is downward. Move down-left to (1, 0).

    • Step 3: (1, 0): Add 4.
      Continue downward: (2, –1) → Out of bounds (col -1).
      Adjust: Since col is out, move down to (2, 0) and flip direction.

    • Step 4: (2, 0): Add 7.
      Now direction is upward. Move up-right to (1, 1).

    • Step 5: (1, 1): Add 5.
      Continue upward: (0, 2).

    • Step 6: (0, 2): Add 3.
      Continue upward: (–1, 3) → Out of bounds.
      Adjust: Since row is out, move right to (0+? check boundary) – actually, when at top row and moving upward, we move to next row if col is not at the last column. Here, we are at (0,2) and col is the last column so we move down to (1,2) and flip direction.

    • Step 7: (1, 2): Add 6.
      Now direction is downward. Move down-left to (2, 1).

    • Step 8: (2, 1): Add 8.
      Continue downward: (3, 0) → Out of bounds (row becomes 3).
      Adjust: Move right to (2, 2) and flip direction.

    • Step 9: (2, 2): Add 9.

    • End traversal as all elements are covered.

  3. Result:
    The result list is [1, 2, 4, 7, 5, 3, 6, 8, 9].

Code Implementation

Python Code

Python3
Python3

. . . .

Java Code

Java
Java

. . . .

Complexity Analysis

  • Time Complexity:

    • We visit each element in the matrix exactly once, so the time complexity is O(m * n).
  • Space Complexity:

    • The output array uses O(m * n) space.
    • The simulation itself uses a constant amount of extra space, i.e., O(1).

Common Mistakes and Edge Cases

  1. Boundary Conditions:

    • Not correctly handling the cases when the current index goes out of bounds. Always check if you are at the first or last row/column before moving.
  2. Direction Toggle:

    • Forgetting to flip the direction when a boundary is hit can lead to incorrect traversal.
  3. Empty Matrix:

    • Always check for an empty matrix and return an empty list/array accordingly.
  4. Single Row or Single Column:

    • Ensure your solution handles matrices with only one row or one column properly.
  • Grouping by Diagonals:
    Instead of simulating movement, you can group elements by the sum of indices (i + j) and then reverse alternate groups.

  • Spiral Order Traversal:
    Another popular matrix traversal problem where you return elements in spiral order.

  • Zigzag Level Order Traversal of a Binary Tree:
    A similar concept where nodes of a binary tree are traversed in a zigzag (alternating) manner.

  • Spiral Matrix
  • Zigzag Level Order Traversal
  • Matrix Block Sum
  • Set Matrix Zeroes
TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Grokking the Advanced System Design Interview: A Detailed Breakdown
Master advanced system design interviews with this detailed breakdown. Learn key concepts, real-world examples, and expert strategies to ace your next interview.
What is the DP problem?
How to prepare for coding interviews in Haskell?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.
;