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.
1function construct2DArray(original, m, n) {
2 if (original.length !== m * n) return [];
3 const result = [];
4 for (let i = 0; i < m; i++) {
5 result.push(original.slice(i * n, (i + 1) * n));
6 }
7 return result;
8}
This JavaScript code uses slice to achieve a similar effect as list comprehension in Python, efficiently creating rows from the original array.
It checks for a valid transformation and constructs the 2D array by slicing the original array for each row.
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.
1function construct2DArray(original, m, n) {
2 if (original.length !== m * n) return [];
3 const result = Array.from({ length: m }, () => Array(n));
4 let index = 0;
5 for (let i = 0; i < m; i++) {
6 for (let j = 0; j < n; j++) {
7 result[i][j] = original[index++];
8 }
9 }
10 return result;
11}
This JavaScript solution aligns with the concept of iterating through all elements, using index tracking and nested loops to allocate each value correctly in the newly formed 2D array.