Similar Problems

Similar Problems not available

Convert An Array Into A 2d Array With Conditions - Leetcode Solution

Companies:

LeetCode:  Convert An Array Into A 2d Array With Conditions Leetcode Solution

Difficulty: Medium

Topics: hash-table array  

Problem statement:

Given a 1d array of integers and an integer n representing the number of rows, convert the 1d array into a 2d array such that each row contains n elements. If the original array does not have enough elements to fill each row, fill the remaining elements with 0. If the original array has more elements than needed to fill the 2d array, ignore the remaining elements.

Example:

Input: [1, 2, 3, 4, 5, 6, 7], n = 3 Output: [[1, 2, 3], [4, 5, 6], [7, 0, 0]]

Solution:

To solve this problem, we need to determine the number of rows that will be needed in the 2d array. We can do this by dividing the length of the 1d array by n and taking the ceiling of the result. The ceiling function ensures that we get an integer result even if the division is not exact. Once we have determined the number of rows, we can create an empty 2d array with the specified number of rows and n columns.

Next, we need to loop through the original 1d array and populate the 2d array accordingly. We can use two nested loops, one for the rows and one for the columns. The outer loop iterates through the rows and the inner loop iterates through the columns for each row. During each iteration, we check if there are any remaining elements in the 1d array. If there are, we add the next element to the current position in the 2d array. If not, we fill the position with 0 instead.

Finally, we return the filled 2d array as the result.

Here is the Python code for the solution:

def convertTo2D(nums, n): numRows = -(-len(nums) // n) res = [[0] * n for _ in range(numRows)] i = 0 for r in range(numRows): for c in range(n): if i < len(nums): res[r][c] = nums[i] i += 1 return res

Example usage

result = convertTo2D([1, 2, 3, 4, 5, 6, 7], 3) print(result) # Output: [[1, 2, 3], [4, 5, 6], [7, 0, 0]]

Convert An Array Into A 2d Array With Conditions Solution Code

1