Convert 1D Array Into 2D Array - Problem
Given a 1-dimensional integer array called
The transformation follows a simple rule: fill the 2D array row by row using elements from the original array in order. The first
Important: If it's impossible to create an m × n matrix using all elements from the original array (i.e., when
Example: Array
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
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
✓ Linear Growth
Space Complexity
O(m × n)
We create a new 2D array of size m×n to store the result
⚡ 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code