We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Convert 1D Array Into 2D Array

Number: 2132

Difficulty: Easy

Paid? No

Companies: Google, Amazon, Meta


Problem Description

Given a 1D integer array named original and two integers m and n, construct a 2D array with m rows and n columns using all the elements from original. The first n elements form the first row, the next n elements form the second row, and so on. If the number of elements in original does not equal m * n, return an empty 2D array.


Key Insights

  • Ensure the total number of elements in original is exactly m * n; otherwise, constructing the desired 2D array is impossible.
  • Use slicing or index arithmetic to break original into chunks of n elements.
  • The simulation approach works by iteratively creating each row from the original array.

Space and Time Complexity

Time Complexity: O(m * n)
Space Complexity: O(m * n)


Solution

The solution checks whether the length of original matches m * n. If not, it immediately returns an empty 2D array. If the size requirement is met, iterate over the original array and slice it into segments of length n to form each row of the 2D array. This method leverages array slicing (or index arithmetic) to organize the elements correctly and build the required matrix.


Code Solutions

# Function to convert 1D array into 2D array
def construct2DArray(original, m, n):
    # Check if total elements equal m * n
    if len(original) != m * n:
        return []  # Return empty 2D array if condition is not met

    # Construct the 2D array by slicing original into chunks of n elements
    return [original[i * n:(i + 1) * n] for i in range(m)]

# Example usage:
print(construct2DArray([1, 2, 3, 4], 2, 2))  # Output: [[1, 2], [3, 4]]
← Back to All Questions