Convert 1D Array Into 2D Array - Problem
Given a 1-dimensional integer array called original and two integers m (rows) and n (columns), your task is to reshape the 1D array into a 2D matrix of size m × n.

The transformation follows a simple rule: fill the 2D array row by row using elements from the original array in order. The first n elements form the first row, the next n elements form the second row, and so on.

Important: If it's impossible to create an m × n matrix using all elements from the original array (i.e., when original.length ≠ m × n), return an empty 2D array.

Example: Array [1,2,3,4,5,6] with m=2, n=3 becomes:
[[1,2,3], [4,5,6]]

Input & Output

example_1.py — Basic Transformation
$ Input: original = [1,2,3,4], m = 2, n = 2
Output: [[1,2],[3,4]]
💡 Note: The original array has 4 elements, and we need a 2×2 matrix (4 cells total). First row gets elements [1,2], second row gets [3,4].
example_2.py — Impossible Case
$ Input: original = [1,2,3], m = 1, n = 2
Output: []
💡 Note: The original array has 3 elements, but a 1×2 matrix only has 2 cells. Since 3 ≠ 1×2, transformation is impossible.
example_3.py — Single Row
$ Input: original = [1,2,3,4,5,6], m = 1, n = 6
Output: [[1,2,3,4,5,6]]
💡 Note: All 6 elements fit into a single row with 6 columns, creating a 1×6 matrix.

Visualization

Tap to expand
Converting 1D Array [1,2,3,4,5,6] to 2×3 MatrixOriginal Array:1234562D Matrix (2 rows × 3 columns):123456Row 0:Row 1:Sequential Filling Process:1. Check: length(6) == m×n(2×3) ✓2. Fill first row: elements 0,1,2 → [1,2,3]3. Fill second row: elements 3,4,5 → [4,5,6]4. Result: [[1,2,3], [4,5,6]]Time: O(m×n) | Space: O(m×n) for result💡 Key insight: Fill sequentially rather than calculating each position
Understanding the Visualization
1
Validate Dimensions
Check if total books equals shelf capacity (original.length == m × n)
2
Create Empty Shelf
Set up the bookshelf with m rows and n columns
3
Fill Row by Row
Take books from the line in order and fill each shelf row completely
4
Complete Arrangement
Continue until all books are placed on the shelf
Key Takeaway
🎯 Key Insight: Instead of calculating index mappings for each position, simply iterate through the original array once and fill the 2D matrix row by row sequentially.

Time & Space Complexity

Time Complexity
⏱️
O(m × n)

We visit each cell in the m×n matrix exactly once, performing constant work per cell

n
2n
Linear Growth
Space Complexity
O(m × n)

We create a new 2D array of size m×n to store the result

n
2n
Linearithmic Space

Constraints

  • 1 ≤ original.length ≤ 5 × 104
  • 1 ≤ original[i] ≤ 105
  • 1 ≤ m, n ≤ 4 × 104
  • Key constraint: Array length must equal m × n for valid transformation
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~8 min Avg. Time
892 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