#2022

Convert 1D Array Into 2D Array

Easy
ArrayMatrixSimulationArrayMatrix
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach leverages the fact that we can directly compute the indices for the 2D array without needing nested loops. This reduces unnecessary complexity and improves performance.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if m * n is equal to the length of the original array. If not, return an empty array.
  2. 2Step 2: Create a new 2D array of size m x n.
  3. 3Step 3: Use a single loop to fill the 2D array by calculating the row and column indices directly.
solution.py9 lines
1# Full working Python code
2
3def construct2DArray(original, m, n):
4    if m * n != len(original):
5        return []
6    result = [[0] * n for _ in range(m)]
7    for i in range(len(original)):
8        result[i // n][i % n] = original[i]
9    return result

Complexity note: The time complexity is O(n) because we only iterate through the original array once. The space complexity is also O(n) due to the new 2D array created.

  • 1The total number of elements must match the dimensions of the desired 2D array.
  • 2Directly calculating indices can simplify the logic and improve performance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.