algoadvance

You are given a 1D array original and two integers, m and n, which represent the dimensions of a 2D array. You need to transform the 1D array into a 2D array with m rows and n columns. If it is not possible to meet the desired dimensions, return an empty 2D array.

Clarifying Questions

  1. What should be the output if the conversion is not possible?
    • If the conversion is not possible, return an empty 2D array.
  2. Will the input always be a valid 1D array?
    • Yes, you can assume that the input is always a valid 1D array.
  3. Can m or n be zero or negative?
    • No, m and n will always be positive integers.

Strategy

  1. Check if Conversion is Possible:
    • The conversion is possible if the length of the original array equals m * n.
    • If not, return an empty list.
  2. Reshape the Array:
    • Iterate over the elements of original and fill a 2D array row by row.

Code

def construct2DArray(original, m, n):
    # Check if conversion is possible
    if len(original) != m * n:
        return []

    # Initialize the 2D array
    result = []
    for i in range(m):
        # Create a row and insert the correct elements
        row = original[i * n:(i + 1) * n]
        result.append(row)

    return result

# Example usage:
original = [1, 2, 3, 4]
m = 2
n = 2
print(construct2DArray(original, m, n))  # Output: [[1, 2], [3, 4]]

Time Complexity

Feel free to ask if you have any further questions or need additional clarifications!

Try our interview co-pilot at AlgoAdvance.com