2022. Convert 1D Array Into 2D Array
Approach
Validate m*n == len; fill 2D array row by row from 1D index.
Key Techniques
Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.
Matrix problems often involve BFS/DFS flood fill, dynamic programming on 2D grids, or spiral/diagonal traversal. For row × column DP, break it into 1D sub-problems column by column. Common pitfalls: boundary checks and modifying the input matrix in-place.
Simulation problems require implementing the described process step by step. Focus on correctly handling edge cases and state transitions. Common in geometry, game problems, and string manipulation. Optimize only if the naive simulation exceeds the time limit.
// Approach: Validate m*n == len; fill 2D array row by row from 1D index.
// Time: O(mn) Space: O(mn)
public class Solution
{
public int[][] Construct2DArray(int[] original, int m, int n)
{
int[][] result = new int[m][];
if ((m * n) != original.Length)
return new int[0][];
int k = 0;
for (int i = 0; i < m; i++)
{
result[i] = new int[n];
for (int j = 0; j < n; j++)
{
result[i][j] = original[k++];
}
}
return result;
}
}