Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Convert 1D Array Into 2D Array

XPChallenge Points: 10
levelLevel: Easy

You are given a one-dimensional array named original and two integers m and n.
Your task is to place all the elements of original into a two-dimensional array that has m rows and n columns.

The first n elements go in the first row, the next n elements go in the second row, and so on.

If the number of elements in original does not exactly match m * n, then return an empty 2D array because it cannot be reshaped properly.

Example 1:

Input: original = [5, 6, 7, 8, 9, 10], m = 3, n = 2

Output: [[5, 6], [7, 8], [9, 10]]

Example 2:

Input: original = [4, 1, 0, 3], m = 2, n = 3

Output: []

Explanation:

Total elements = 4 but needed = 6 → cannot form matrix.

Example 3:

Input: original = [9], m = 1, n = 1

Output: [[9]]

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result