Convert 1D Array Into 2D Array - Problem

You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original.

The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on.

Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.

Input & Output

Example 1 — Basic Conversion
$ Input: original = [1,2,3,4], m = 2, n = 2
Output: [[1,2],[3,4]]
💡 Note: Elements 0-1 form first row [1,2], elements 2-3 form second row [3,4], creating a 2×2 matrix
Example 2 — Impossible Case
$ Input: original = [1,2,3], m = 1, n = 5
Output: []
💡 Note: Need 1×5 = 5 elements but only have 3 elements, so return empty array
Example 3 — Single Row
$ Input: original = [1,2], m = 1, n = 2
Output: [[1,2]]
💡 Note: All elements fit in one row: [1,2] becomes [[1,2]]

Constraints

  • 1 ≤ original.length ≤ 5 × 104
  • 1 ≤ original[i] ≤ 105
  • 1 ≤ m, n ≤ 4 × 104

Visualization

Tap to expand
Convert 1D Array Into 2D Array INPUT 1D Array: original 1 2 3 4 idx 0 idx 1 idx 2 idx 3 Parameters: m = 2 n = 2 m = rows, n = columns Validation Check: m * n = 2 * 2 = 4 = len OK - Valid conversion! ALGORITHM STEPS 1 Validate Size Check: m * n == original.length 2 Create 2D Array Initialize result[m][n] 3 Index Calculation row = i / n, col = i % n 4 Fill Elements result[row][col] = original[i] Index Mapping (n=2): i=0: 0/2=0, 0%2=0 --> [0][0] i=1: 1/2=0, 1%2=1 --> [0][1] i=2: 2/2=1, 2%2=0 --> [1][0] i=3: 3/2=1, 3%2=1 --> [1][1] FINAL RESULT 2D Array: result row 0 1 2 row 1 3 4 col 0 col 1 Output: [[1,2],[3,4]] Conversion Complete! 2 rows x 2 columns All 4 elements placed Key Insight: The index formula row = i / n and col = i % n allows single-pass conversion. Integer division gives row number, modulo gives column position. Time: O(m*n), Space: O(1) extra. TutorialsPoint - Convert 1D Array Into 2D Array | Single Pass with Index Calculation
Asked in
Facebook 15 Amazon 12 Google 8
28.5K Views
Medium Frequency
~12 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen