You are given a 1D array original
and two integers, m
and n
, which represent the dimensions of a 2D array. You need to transform the 1D array into a 2D array with m
rows and n
columns. If it is not possible to meet the desired dimensions, return an empty 2D array.
m
or n
be zero or negative?
m
and n
will always be positive integers.original
array equals m * n
.original
and fill a 2D array row by row.def construct2DArray(original, m, n):
# Check if conversion is possible
if len(original) != m * n:
return []
# Initialize the 2D array
result = []
for i in range(m):
# Create a row and insert the correct elements
row = original[i * n:(i + 1) * n]
result.append(row)
return result
# Example usage:
original = [1, 2, 3, 4]
m = 2
n = 2
print(construct2DArray(original, m, n)) # Output: [[1, 2], [3, 4]]
O(m * n)
or equivalently O(len(original))
O(m * n)
Feel free to ask if you have any further questions or need additional clarifications!
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?