In the Diagonal Traverse II coding problem, you are given a 2D list of integers where each row can have a different length (a "jagged" array). You need to return all elements in diagonal order, starting from the bottom-left of each diagonal and moving up-right. Unlike version I, there is no zig-zagging; every diagonal is traversed in the same direction.
Apple and Amazon use this to test your ability to handle non-rectangular grids. Since you don't know the column length for each row, you cannot easily predict where a diagonal starts or ends. It evaluations your skill in using Hash Tables to group elements by their diagonal index or using BFS to explore the grid level by level.
There are two effective patterns:
List<List<Integer>> where the outer list index is . Since you visit rows from top to bottom, the elements will naturally be in the reverse order of the required up-right traversal. Reverse each inner list at the end.Grid:
1 2 3
4
5 6
{0: [1]}.{0: [1], 1: [2]}.{0: [1], 1: [2], 2: [3]}.{..., 1: [2, 4]}.{..., 2: [3, 5]}.{..., 3: [6]}.
Final (after reversing groups): [1, 4, 2, 5, 3, 6].Map<Integer, List<Integer>> when the total number of diagonals is large.For jagged arrays, avoid index-based traversal (for i, for j) if possible. BFS or grouping by an invariant (like ) are much more robust against varying row lengths.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Single-Threaded CPU | Medium | Solve | |
| Campus Bikes | Medium | Solve | |
| Choose K Elements With Maximum Sum | Medium | Solve | |
| Find the K-Sum of an Array | Hard | Solve | |
| Maximum Product of Two Elements in an Array | Easy | Solve |