Leetcode 2022. Convert 1D Array Into 2D Array
You are given a 1D array original
and two integers m
and n
. You are required to write a function that reshapes the 1D array into a 2D array with m
rows and n
columns.
If it is not possible to reshape the array due to mismatch in total size, return an empty 2D array.
original = [1, 2, 3, 4]
m = 2
n = 2
[[1, 2], [3, 4]]
original = [1, 2, 3]
m = 1
n = 3
[[1, 2, 3]]
original = [1, 2]
m = 1
n = 1
[]
original
is empty?
original
is empty and m
and n
are both zero, return an empty 2D array. If m
or n
are non-zero, return an empty array as reshaping is not possible.original
always positive integers?
m
or n
are less than or equal to zero?
original
with m * n
.m
by n
.Here’s the C++ code to convert the 1D array into a 2D array:
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
int totalSize = original.size();
if (totalSize != m * n) {
return vector<vector<int>>(); // Return an empty vector if reshaping is not possible
}
vector<vector<int>> result(m, vector<int>(n, 0));
for (int i = 0; i < totalSize; ++i) {
result[i / n][i % n] = original[i];
}
return result;
}
};
The time complexity for this solution is O(m * n) or O(totalSize) because we are iterating over the original
array exactly once to fill the 2D array. The auxiliary space complexity is O(1), excluding the space needed for the result vector.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?