Convert 1D Array Into 2D Array — LeetCode 2022 Python Solution

EasyArrayMatrixSimulation
Problem
#2022
Reading time
2 min

The problem

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.

Example

Input
original = [1,2,3,4], m = 2, n = 2
Output
[[1,2],[3,4]]
Explanation
The constructed 2D array should contain 2 rows and 2 columns.

Python solution

Python
class Solution:
    def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
        if m * n != len(original):
            return []
        return [original[i : i + n] for i in range(0, m * n, n)]

Complexity

MeasureComplexity
TimeO(m \times n), where m and n are the number of rows and columns of the two-dimensional array, respectively
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2022. Convert 1D Array Into 2D Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2022. Convert 1D Array Into 2D Array?
LeetCode 2022. Convert 1D Array Into 2D Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 2022. Convert 1D Array Into 2D Array?
The Python solution on this page runs in O(m \times n), where m and n are the number of rows and columns of the two-dimensional array, respectively.
What is the space complexity of LeetCode 2022. Convert 1D Array Into 2D Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2022. Convert 1D Array Into 2D Array cover?
LeetCode 2022. Convert 1D Array Into 2D Array is tagged Array, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview