Leetcode 2022: Convert 1D Array Into 2D Array

grid47
grid47
Exploring patterns and algorithms
Apr 18, 2024 4 min read

You are given a 1D integer array called ‘original’ and two integers ’m’ and ’n’. Your task is to convert this 1D array into a 2D array with ’m’ rows and ’n’ columns. The elements from the ‘original’ array should be placed row-wise in the new 2D array.
Problem
Approach
Steps
Complexity
Input: The input consists of a 1D integer array 'original' and two integers 'm' and 'n'.
Example: original = [1, 2, 3, 4], m = 2, n = 2
Constraints:
• 1 <= original.length <= 5 * 10^4
• 1 <= original[i] <= 10^5
• 1 <= m, n <= 4 * 10^4
Output: Return the newly constructed 2D array, or an empty array if it is impossible to fit the elements.
Example: Output: [[1, 2], [3, 4]]
Constraints:
• The 2D array must have m rows and n columns if possible.
Goal: To check if it's possible to fit the elements into a 2D array and construct it row-wise.
Steps:
• 1. Check if m * n equals the length of the original array. If not, return an empty array.
• 2. Create a new 2D array and populate each row with 'n' elements from the original array.
Goal: The constraints on the input values.
Steps:
• 1 <= original.length <= 5 * 10^4
• 1 <= original[i] <= 10^5
• 1 <= m, n <= 4 * 10^4
Assumptions:
• The input array has at least 1 element.
• The integers m and n are both greater than or equal to 1.
Input: original = [1, 2, 3, 4], m = 2, n = 2
Explanation: The original array has 4 elements, and it can be evenly split into 2 rows and 2 columns.

Input: original = [1, 2], m = 1, n = 1
Explanation: There are 2 elements in the original array, but it's impossible to fit them into a 1x1 matrix.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus