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.
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 for (int i = 0; i < original.size(); ++i) {
8 matrix[i / n][i % n] = original[i];
9 }
10 return matrix;
11}
This C++ solution directly checks if the total size matches m * n.
Using division and modulo operations, it calculates the correct position of each element of the 1D array in the 2D array.
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.
1def construct2DArray(original: List[int], m: int, n: int) -> List[List[int]]:
2 if len(original) != m * n:
3 return []
4 result = [[0] * n for _ in range(m)]
5 for i in range(m):
6 for j in range(n):
7 result[i][j] = original[i * n + j]
8 return result
In Python, we check if the transformation is due, initialize a zero-filled 2D array, and populate it iteratively by navigating over rows and columns with explicit assignments.