Source Code: class Solution: def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]: ''' To solve this problem, we can create a new 2D array with the given dimensions, iterate through the original array and put those values from the original array onto our new 2d array as we iterate through it. We can quickly identify an invalid array by taking a look at the number of elements the original array has. If the given dimensions (row by column) total arrays doesn't equal the length of the original array (total arrays), that means that the size will be invalid :D ''' if len(original) != (m*n): return [] new_arr = [[0]*n for _ in range(m)] counter = 0 for i in range(m): for j in range(n): new_arr[i][j] = original[counter] counter += 1 return new_arr
Source Code:
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
'''
To solve this problem, we can create a new 2D array with
the given dimensions, iterate through the original array
and put those values from the original array onto
our new 2d array as we iterate through it. We can quickly
identify an invalid array by taking a look at the number of
elements the original array has. If the given dimensions
(row by column) total arrays doesn't equal the length
of the original array (total arrays), that means that
the size will be invalid :D
'''
if len(original) != (m*n):
return []
new_arr = [[0]*n for _ in range(m)]
counter = 0
for i in range(m):
for j in range(n):
new_arr[i][j] = original[counter]
counter += 1
return new_arr