LeetCode 1424: Diagonal Traverse II Solution

Master LeetCode problem 1424 (Diagonal Traverse II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1424. Diagonal Traverse II

Problem Explanation

Explanation

To traverse the array diagonally, we need to move in a zigzag pattern. We can achieve this by keeping track of the diagonal index sum (i+j) and storing elements in a map based on this sum. Then we can iterate through the map to get the elements in the desired order.

  1. Create a map to store elements based on the diagonal index sum (i+j).
  2. Traverse the 2D array and store elements in the map.
  3. Iterate through the map and add elements to the result list.

Time Complexity: O(N*M) where N is the number of rows and M is the number of columns in the input array.

Space Complexity: O(N*M) for storing elements in the map.

Solution Code

import java.util.*;

class Solution {
    public int[] findDiagonalOrder(List<List<Integer>> nums) {
        Map<Integer, List<Integer>> map = new HashMap<>();
        int rows = nums.size();
        int resultSize = 0;

        for (int i = 0; i < rows; i++) {
            List<Integer> row = nums.get(i);
            int cols = row.size();
            for (int j = 0; j < cols; j++) {
                int diagonalSum = i + j;
                map.putIfAbsent(diagonalSum, new ArrayList<>());
                map.get(diagonalSum).add(row.get(j));
                resultSize++;
            }
        }

        int[] result = new int[resultSize];
        int idx = 0;
        for (int key : map.keySet()) {
            List<Integer> diagonalElements = map.get(key);
            for (int i = diagonalElements.size() - 1; i >= 0; i--) {
                result[idx++] = diagonalElements.get(i);
            }
        }

        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1424 (Diagonal Traverse II)?

This page provides optimized solutions for LeetCode problem 1424 (Diagonal Traverse II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1424 (Diagonal Traverse II)?

The time complexity for LeetCode 1424 (Diagonal Traverse II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1424 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1424 in Java, C++, or Python.

Back to LeetCode Solutions