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.
1public class Solution {
2 public int[][] Construct2DArray(int[] original, int m, int n) {
3 if (original.Length != m * n) return new int[0][];
4 int[][] result = new int[m][];
5 for (int i = 0; i < m; i++) {
6 result[i] = new int[n];
7 for (int j = 0; j < n; j++) {
8 result[i][j] = original[i * n + j];
9 }
10 }
11 return result;
12 }
13}
In this C# implementation, the program validates that the original array can be transformed into the desired 2D form by comparing its length to m * n.
It then constructs each row of the 2D array within a nested loop, mimicking the mapping from 1D to 2D.
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.
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 int index = 0;
6 for (int i = 0; i < m; i++) {
7 for (int j = 0; j < n; j++) {
8 result[i][j] = original[index++];
9 }
10 }
11 return result;
12 }
13}
Java solution proceeds after validating the dimensions, employing an index tracker to map every 1D element into their respective 2D space using two nested loops for traversal.