Similar Problems

Similar Problems not available

Convert 1d Array Into 2d Array - Leetcode Solution

Companies:

LeetCode:  Convert 1d Array Into 2d Array Leetcode Solution

Difficulty: Easy

Topics: matrix array simulation  

Problem Statement: Given a 1D array, write a function to convert it to a 2D array with given number of rows and columns.

Example 1: Input: nums = [1,2,3,4], r = 2, c = 2 Output: [[1,2],[3,4]] Explanation: The given array can be converted to a 2D array as: 1 2 3 4

Example 2: Input: nums = [1,2,3,4,5,6], r = 3, c = 2 Output: [[1,2],[3,4],[5,6]] Explanation: The given array can be converted to a 2D array as: 1 2 3 4 5 6

Solution: To solve this problem, we first need to check whether total elements in the 1D array are equal to the desired size of 2D array. If they are not equal, then we return the given array since we cannot convert it into a 2D array with the given size.

If the total elements in the 1D array are equal to the desired size of 2D array, we can start converting the array into a 2D array. We can declare the 2D array and start filling elements row by row from the 1D array.

Here's the step by step solution in Python:

def convert(nums, r, c): n = len(nums) if n != r * c: return nums

res = [[0]*c for _ in range(r)]
for i in range(r):
    for j in range(c):
        res[i][j] = nums[i*c+j]
return res

Testing the function with example inputs

print(convert([1,2,3,4], 2, 2)) # [[1,2],[3,4]] print(convert([1,2,3,4,5,6], 3, 2)) # [[1,2],[3,4],[5,6]]

Let's understand the above code:

  • We first check if the total elements in the 1D array is not equal to r*c, we return the given array since it cannot be converted into a 2D array.
  • We create the 2D array res by initializing it with 0s with length of c in each row and creating r such rows.
  • We loop through each element of the 2D array and fill it with the corresponding element from the 1D array.
  • We finally return the 2D array.

Time Complexity: O(mn) where m is the number of rows and n is the number of columns.

Space Complexity: O(mn) as we need to store the 2D array.

Convert 1d Array Into 2d Array Solution Code

1