LeetCode 2022: Convert 1D Array Into 2D Array Solution

Master LeetCode problem 2022 (Convert 1D Array Into 2D Array), a easy 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.

2022. Convert 1D Array Into 2D Array

Problem Explanation

Explanation

To solve this problem, we need to iterate through the original array and construct a 2D array with m rows and n columns. We can achieve this by checking if the total number of elements in the original array matches the number of elements required for the 2D array. If it does, we can iterate through the original array and populate the 2D array row by row. If not, we return an empty 2D array.

  • Time complexity: O(m*n)
  • Space complexity: O(m*n)

Solution Code

class Solution {
    public int[][] construct2DArray(int[] original, int m, int n) {
        if (original.length != m * n) {
            return new int[0][0];
        }

        int[][] result = new int[m][n];
        int index = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                result[i][j] = original[index++];
            }
        }

        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2022 (Convert 1D Array Into 2D Array)?

This page provides optimized solutions for LeetCode problem 2022 (Convert 1D Array Into 2D Array) 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 2022 (Convert 1D Array Into 2D Array)?

The time complexity for LeetCode 2022 (Convert 1D Array Into 2D Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2022 on DevExCode?

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

Back to LeetCode Solutions