Convert 1D Array Into 2D Array
What is this problem about?
The Convert 1D Array Into 2D Array interview question asks you to transform a linear array into a 2D matrix with m rows and n columns. If the total number of elements in the 1D array does not match m * n, you must return an empty 2D array.
Why is this asked in interviews?
This Convert 1D Array Into 2D Array coding problem is an "Easy" task common at Google and Amazon. It tests basic indexing logic and understanding of memory layout. It's a fundamental check to see if a candidate can map a flat index to (row, column) coordinates.
Algorithmic pattern used
This follows the Array, Matrix, Simulation interview pattern.
- Flat index i maps to:
- Row: i / n (integer division)
- Column: i % n (modulo)
- You initialize a 2D array of size m x n and fill it in a single pass.
Example explanation
Input: [1, 2, 3, 4], m=2, n=2
- Check: 4 == 2 * 2. Proceed.
- Index 0: Row 0/2=0, Col 0%2=0. matrix[0][0] = 1.
- Index 1: Row 1/2=0, Col 1%2=1. matrix[0][1] = 2.
- Index 2: Row 2/2=1, Col 2%2=0. matrix[1][0] = 3.
- Index 3: Row 3/2=1, Col 3%2=1. matrix[1][1] = 4.
Result: [[1, 2], [3, 4]].
Common mistakes candidates make
- Off-by-one errors: Miscalculating the column boundary or row transition.
- Incorrect sizing: Not returning an empty array when the input length is invalid.
- Manual looping: Using complex nested loops when a simple map from i to (r, c) is cleaner.
Interview preparation tip
Master the "Coordinate Mapping" formulas. They are used in almost every matrix problem, from 2D traversals to image rotation and flattening.