Leetcode Daily Question 01/09/2024 - 2022. Convert 1D Array Into 2D Array

Problem Description:

You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original. The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.

Solution:

from typing import List
class Solution:
  def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
    if m * n != len(original):
      return []
    
    new_matrix = []
    for i in range(m):
      new_matrix.append(original[n * i: n * (i + 1)])
    
    return new_matrix

Explanation:

The most efficient way to do this is to handle the case where it is impossible to construct a valid matrix. Then to construct the matrix row by row.

To be a valid matrix, we need the dimensions of matrix to match up to the size of the original array.

if m * n != len(original):
  return []

To construct the matrix row by row. We iterate the matrix in blocks of n, and append this sub-array of the original array to our new_matrix.

new_matrix = []
for i in range(m):
  new_matrix.append(original[n * i: n * (i + 1)]) # blocks of n 
  
return new_matrix

The time complexity is O(n) as we need to pass the original array exactly once to create our new matrix.

The space complexity is O(n) since the dimension of the matrix is the same as the size of the original array.

The full solution can be found near the top of the page.

Back