Diagonal Traversal of Matrix
Index GroupingSolved Nov 8, 2025
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 130 pointsSolved (Medium) 0/40Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Watch the concept video if the pattern is new to you.
Step 2
Try it on paper
5–10 minutes, no code yet
ProblemProblem statementGiven a 2D matrix, traverse and print its elements diagonally (usually starting from the top-left, alternating direction for each diagonal).ReadHide
Problem Description
Given a 2D matrix, traverse and print its elements diagonally (usually starting from the top-left, alternating direction for each diagonal).
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
Elements on the same anti-diagonal share the same sum of indices (i + j). Group elements by this sum and process the groups.
Approaches
1. Index Grouping with Hashing (Optimal) - O(N²) ⭐
Idea: The elements belonging to the same diagonal share a constant property: the sum of their indices (i+j).
- Group: Iterate through the matrix, calculating the sum
S = i + j. Use a hash map (or array) where the key isSand the value is a list of elements belonging to that diagonal. - Order: Iterate through the map keys (sums) from 0 to
2N-2, printing the elements of each list. Additional logic is needed if the problem requires the traversal to alternate direction (up-right vs. down-left).
Time: O(N²) (Reading and grouping)
Space: O(N²) (To store all grouped elements).
Solution code
import sys
from collections import defaultdict
def diagonalTraversal_optimal(matrix):
"""O(N^2) Time, O(N^2) Space - Index Grouping with Alternating Reversal"""
if not matrix or not matrix[0]: return []
R = len(matrix)
C = len(matrix[0])
# Use defaultdict for clean grouping
diagonals = defaultdict(list)
# 1. Group elements by the sum of their indices (i + j)
for i in range(R):
for j in range(C):
diagonals[i + j].append(matrix[i][j])
# 2. Traverse the diagonals in order (keys are sorted automatically)
result = []
for sum_val in sorted(diagonals.keys()):
current_diagonal = diagonals[sum_val]
# Reverse every other diagonal (based on index sum's parity)
if sum_val % 2 == 0:
# Reverse only for odd sums if starting up-right, reverse for even sums if starting down-left.
# Standard implementation (like LeetCode 498) requires reversal based on sum parity.
current_diagonal.reverse()
result.extend(current_diagonal)
# Print the space-separated output
print(" ".join(map(str, result)))Other ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language