Diagonal Traverse II

Medium Arrays & Hashing Matrix Traversal

Reported atMeta

Diagonal Traverse II is a medium arrays & hashing problem solved with the matrix traversal pattern. The best approach, optimal (bfs from the top-left cell), runs in O(N) time and O(N) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (walk every diagonal of the bounding box) up.

Problem

You are given nums, a list of rows of integers. The rows do not have to be the same length. Number the anti-diagonals by d = i + j, where i is the row and j the column of a value. Return every value of nums in one array: first diagonal 0, then diagonal 1, and so on, and within one diagonal list the values from the bottom row (largest i) up to the top row (smallest i). Positions that do not exist because a row is too short are simply skipped.

Examples

Example 1

Input
nums = [[5,8,2],[4,6],[9,1,7,3]]
Output
[5,4,8,9,6,2,1,7,3]
Why
Diagonal 0 holds 5. Diagonal 1 holds 4 (row 1) then 8 (row 0). Diagonal 2 holds 9, 6, 2 from the bottom row up. Diagonals 3, 4 and 5 each hold one value of the last row: 1, 7 and 3.

Example 2

Input
nums = [[3],[7,2,8,6],[1]]
Output
[3,7,1,2,8,6]
Why
Diagonal 2 is the only one with two values: 1 from row 2 comes before 2 from row 1. Rows 0 and 2 are short, so the later diagonals only touch row 1.

Example 3

Input
nums = [[4],[2],[9]]
Output
[4,2,9]
Why
Every row has one value, so each value sits alone on its own diagonal and the order is simply top to bottom.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i].length <= 10^5
  • 1 <= sum of all nums[i].length <= 10^5
  • 1 <= nums[i][j] <= 10^5

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 45 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (walk every diagonal of the bounding box)O(rows · maxDiag)O(N)
Group values by diagonalO(N)O(N)
Optimal (BFS from the top-left cell)O(N)O(N)

1Brute force (walk every diagonal of the bounding box)

TimeO(rows · maxDiag)Every diagonal checks every row, even rows too short to reach it. A first row of 50,000 values over 50,000 one-value rows means billions of checks for only 100,000 values.
SpaceO(N)Only the answer array of N values is stored.

Find the largest diagonal index any value sits on. For each diagonal d from 0 up to that, walk the rows from the bottom-most possible row up to row 0, and take the value at column d - i whenever that row is long enough.

  1. Count the values and find maxDiag = max over rows of i + nums[i].length - 1.
  2. For d from 0 to maxDiag, for i from min(d, rows - 1) down to 0: let j = d - i.
  3. If j < nums[i].length, append nums[i][j].
  4. Return the collected values.
class Solution {
    public int[] findDiagonalOrder(List<List<Integer>> nums) {
        int rows = nums.size(), total = 0, maxDiag = 0;
        for (int i = 0; i < rows; i++) {
            total += nums.get(i).size();
            maxDiag = Math.max(maxDiag, i + nums.get(i).size() - 1);
        }
        int[] res = new int[total];
        int k = 0;
        for (int d = 0; d <= maxDiag; d++) {
            for (int i = Math.min(d, rows - 1); i >= 0; i--) {
                int j = d - i;
                if (j < nums.get(i).size()) res[k++] = nums.get(i).get(j);
            }
        }
        return res;
    }
}

2Group values by diagonal

TimeO(N)Each value is appended once and read once, and there are at most N buckets.
SpaceO(N)The buckets together hold all N values.

Each value at (i, j) belongs to bucket i + j. Visit the rows from the last one up to row 0 and append every value to its bucket. Because lower rows are visited first, each bucket fills from the bottom row to the top row, which is the order the answer wants. Then read the buckets in order of their index.

  1. Make a growing list of buckets.
  2. For i from rows - 1 down to 0, for each j in row i: add buckets until index i + j exists, then append nums[i][j] to bucket i + j.
  3. Concatenate the buckets from index 0 upward.
class Solution {
    public int[] findDiagonalOrder(List<List<Integer>> nums) {
        List<List<Integer>> groups = new ArrayList<>();
        int total = 0;
        for (int i = nums.size() - 1; i >= 0; i--) {
            List<Integer> row = nums.get(i);
            for (int j = 0; j < row.size(); j++) {
                while (groups.size() <= i + j) groups.add(new ArrayList<>());
                groups.get(i + j).add(row.get(j));
                total++;
            }
        }
        int[] res = new int[total];
        int k = 0;
        for (List<Integer> g : groups) {
            for (int v : g) res[k++] = v;
        }
        return res;
    }
}

3Optimal (BFS from the top-left cell)

TimeO(N)Each of the N cells is queued and polled exactly once.
SpaceO(N)The answer holds N values; the queue holds at most one diagonal, which is at most the number of rows.

Treat each cell as a node. Cell (i, j) leads to its right neighbour (i, j + 1) when that exists, and a first-column cell (i, 0) also leads to (i + 1, 0) below it. Every cell then has exactly one way in, so nothing is queued twice. A BFS from (0, 0) visits diagonal d before diagonal d + 1, and because the downward step is queued before the rightward one, each diagonal comes out from the bottom row to the top row.

  1. Count the values and make the answer array; queue (0, 0).
  2. Poll (i, j) and write nums[i][j] to the answer.
  3. If j == 0 and row i + 1 exists, queue (i + 1, 0).
  4. If row i has a value at j + 1, queue (i, j + 1).
  5. Repeat until the queue is empty.
class Solution {
    public int[] findDiagonalOrder(List<List<Integer>> nums) {
        int total = 0;
        for (List<Integer> row : nums) total += row.size();
        int[] res = new int[total];
        Deque<int[]> queue = new ArrayDeque<>();
        queue.add(new int[] { 0, 0 });
        int k = 0;
        while (!queue.isEmpty()) {
            int[] cell = queue.poll();
            int i = cell[0], j = cell[1];
            res[k++] = nums.get(i).get(j);
            if (j == 0 && i + 1 < nums.size()) queue.add(new int[] { i + 1, 0 });
            if (j + 1 < nums.get(i).size()) queue.add(new int[] { i, j + 1 });
        }
        return res;
    }
}

Edge cases to test

  • A single value
  • A single long row (the answer is that row)
  • A single column (the answer is the column, top to bottom)
  • A very wide first row over many one-value rows: the bounding box is huge but holds few values
  • Rows of very different lengths, so a diagonal can skip over short rows

Hints

Hint 1

Every cell (i, j) belongs to diagonal i + j. The answer lists diagonal 0, then 1, then 2, and so on.

Hint 2

Walking the full bounding rectangle can cost far more than the number of values when the rows are ragged. Touch only the cells that exist.

Hint 3

Visit rows from the last to the first and append each value to the bucket for i + j: every bucket then comes out bottom to top.

Hint 4

Or run a BFS from (0, 0) where (i, j) leads to (i, j + 1), and also to (i + 1, 0) when j is 0. The queue then holds the cells in exactly the answer order.

FAQ

What is the best time complexity for Diagonal Traverse II?

Optimal (BFS from the top-left cell) runs in O(N) time and O(N) extra space. Each of the N cells is queued and polled exactly once.

Which pattern does Diagonal Traverse II use?

It is a arrays & hashing problem that uses the matrix traversal pattern. Other problems with the same pattern: Spiral Matrix, Best Meeting Point, Diagonal Traverse.

Is there a brute force solution for Diagonal Traverse II?

Yes. Brute force (walk every diagonal of the bounding box) takes O(rows · maxDiag) time and O(N) space. Find the largest diagonal index any value sits on.

Which edge cases should I test for Diagonal Traverse II?

A single value; A single long row (the answer is that row); A single column (the answer is the column, top to bottom); A very wide first row over many one-value rows: the bounding box is huge but holds few values; Rows of very different lengths, so a diagonal can skip over short rows.