This approach involves directly mapping each element from the 1D array to its corresponding position in the 2D array.
The key idea is to iterate over the original array, calculate the correct row and column for each element, and place it accordingly in the 2D array.
If the total number of elements in the original array does not match m * n, return an empty array as it's impossible to fill the 2D array correctly.
Time Complexity: O(m * n), as each element in the original array is accessed exactly once to fill the 2D array.
Space Complexity: O(m * n) for the 2D array itself.
1class Solution {
2 public int[][] construct2DArray(int[] original, int m, int n) {
3 if (original.length != m * n) return new int[0][0];
4 int[][] result = new int[m][n];
5 for (int i = 0; i < original.length; i++) {
6 result[i / n][i % n] = original[i];
7 }
8 return result;
9 }
10}
The Java solution verifies if the number of elements matches m * n before proceeding to fill the new 2D array.
It uses division and modulo to map 1D indices to 2D coordinates optimally.
An alternative approach is to explicitly iterate over each element of the 1D array and place it in the correct position of the 2D array.
This is similar to the direct mapping approach but demonstrates a more explicit handling of indices and 2D placements.
Again, we must first ensure that conversion is feasible by matching the length of the original array and m * n. If not feasible, return an empty array.
Time Complexity: O(m * n). Space Complexity: O(m * n) for memory used in 2D array creation.
1#include <vector>
2using namespace std;
3
4vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
5 if (original.size() != m * n) return {};
6 vector<vector<int>> matrix(m, vector<int>(n));
7 int currentIndex = 0;
8 for (int i = 0; i < m; ++i) {
9 for (int j = 0; j < n; ++j) {
10 matrix[i][j] = original[currentIndex++];
11 }
12 }
13 return matrix;
14}
The C++ implementation uses a similar check and starts filling using a position tracking index, explicitly placing each 1D element in its correct 2D position through a nested loop.