Diagonal Traverse II - Problem
Diagonal Traverse II presents you with a fascinating 2D array traversal challenge! Given a 2D integer array nums (which may have rows of different lengths - a jagged array), your task is to traverse all elements diagonally and return them in a single array.

Unlike a regular matrix, this problem deals with jagged arrays where each row can have a different number of elements. You need to collect elements along each diagonal line, starting from the top-left and moving towards the bottom-right.

Key insight: Elements on the same diagonal share the property that their row + column indices are equal! For example, elements at positions (0,0), (1,0), (0,1) would be on different diagonals with sums 0, 1, and 1 respectively.

Goal: Return all elements traversed diagonally, where within each diagonal, elements are processed from top to bottom.

Input & Output

example_1.py โ€” Python
$ Input: nums = [[1,2,3],[4,5],[6]]
โ€บ Output: [1,2,4,3,5,6]
๐Ÿ’ก Note: Diagonal 0: [1] (sum=0), Diagonal 1: [2,4] (sum=1), Diagonal 2: [3,5,6] (sum=2). Concatenating gives [1,2,4,3,5,6].
example_2.py โ€” Python
$ Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
โ€บ Output: [1,6,8,9,12,2,7,10,13,3,4,11,14,15,5,16]
๐Ÿ’ก Note: Elements are grouped by diagonal sum: D0:[1], D1:[6,8,9,12], D2:[2,7,10,13], D3:[3,4,11,14,15], D4:[5,16]. Within each diagonal, elements appear in row order (top to bottom).
example_3.py โ€” Python
$ Input: nums = [[1,2],[3,4,5,6]]
โ€บ Output: [1,3,2,4,5,6]
๐Ÿ’ก Note: Simple case with two rows. D0:[1], D1:[3,2], D2:[4,5], D3:[6]. Note how elements from different rows can be on the same diagonal.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i].length โ‰ค 105
  • 1 โ‰ค sum(nums[i].length) โ‰ค 105
  • 1 โ‰ค nums[i][j] โ‰ค 106
  • The input represents a jagged 2D array (rows can have different lengths)

Visualization

Tap to expand
Diagonal Traverse II: Pattern RecognitionInput Matrix (Jagged):1(0,0)2(0,1)3(0,2)4(1,0)5(1,1)6(2,0)Diagonal Groups:D0 (sum=0): [1]D1 (sum=1): [2,4]D2 (sum=2): [3,5,6]๐Ÿ”‘ Key: row + col = diagonal ID๐ŸŽฏ Key InsightElements on the same diagonal have the same coordinate sum!This allows us to group them efficiently using a hash map.
Understanding the Visualization
1
Identify Pattern
Elements on same diagonal have equal row + column sums
2
Group Elements
Use coordinate sum as hash key to group diagonal elements
3
Traverse in Order
Process diagonals sequentially from sum 0 to maximum sum
Key Takeaway
๐ŸŽฏ Key Insight: The coordinate sum (row + col) uniquely identifies each diagonal, enabling efficient O(N) grouping and traversal of elements in the correct diagonal order.
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
89.2K Views
High Frequency
~18 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen