Title: Convert Between 1D and 2D Array
Working with arrays in Java often means reshaping data between a flat list and a grid. In this guide, you will learn two complementary techniques: converting a 1D array into a 2D array with a chosen number of rows and columns, and flattening a 2D array back into a single 1D array.
These conversions come up constantly in real code, from reshaping pixel data to normalizing API responses that arrive as a flat buffer. By the end of this guide you will have a reusable ArrayConverter class, a worked trace of the index math, and a set of edge cases and interview follow-ups to sharpen your understanding.
Understanding the Problem
Given a 1D array of n elements, the goal is to place every element into a 2D array with rows rows and cols columns such that rows * cols equals n. The reverse operation takes an existing 2D array and reads it back into a single 1D array, preserving the order in which elements appear row by row.
The core challenge is the index math: an element at position i in the 1D array belongs at row i / cols and column i % cols in the 2D array. Getting this formula wrong, or skipping the size check, is the most common source of bugs in this kind of conversion.
Approach to Convert Between 1D and 2D Arrays
Both directions follow a simple, predictable pattern once you commit to row-major order, where a row is filled completely before moving to the next one.
- Confirm that
oneD.lengthequalsrows * colsbefore allocating anything; throw an exception immediately if it does not. - Allocate a new
int[rows][cols]array to hold the reshaped result. - Loop over every index
ifrom 0 tooneD.length - 1. - Compute the destination row as
i / colsand the destination column asi % cols. - Assign
oneD[i]intotwoD[row][col]. - For the reverse direction, loop over the 2D array with a row index
iand a column indexj, in that nesting order. - Append each
twoD[i][j]to the 1D array at a running index that increments after every assignment.
Java Program
The ArrayConverter class below implements both conversions and demonstrates them with a short main method.
import java.util.Arrays;
public class ArrayConverter {
public static int[][] convertTo2D(int[] oneD, int rows, int cols) {
if (oneD.length != rows * cols) {
throw new IllegalArgumentException("Array size does not match the target dimensions");
}
int[][] twoD = new int[rows][cols];
for (int i = 0; i < oneD.length; i++) {
twoD[i / cols][i % cols] = oneD[i];
}
return twoD;
}
public static int[] convertTo1D(int[][] twoD) {
int rows = twoD.length;
int cols = twoD[0].length;
int[] oneD = new int[rows * cols];
int index = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
oneD[index] = twoD[i][j];
index++;
}
}
return oneD;
}
public static void main(String[] args) {
int[] source = {1, 2, 3, 4, 5, 6};
int[][] matrix = convertTo2D(source, 2, 3);
System.out.println("2D array:");
for (int[] row : matrix) {
System.out.println(Arrays.toString(row));
}
int[] flattened = convertTo1D(matrix);
System.out.println("Flattened back to 1D:");
System.out.println(Arrays.toString(flattened));
}
}Explanation of the Program
convertTo2D first checks that oneD.length matches rows * cols, since any mismatch means the grid cannot hold every element exactly once. It then walks the 1D array once, using integer division and the modulo operator to compute each element’s row and column in the destination grid.
convertTo1D works in the opposite direction. It reads the 2D array’s dimensions from twoD.length and twoD[0].length, then walks every row and column with nested loops, writing each value into the next open slot of the 1D array using a running index variable.
Both methods run in O(n) time, where n is the total number of elements, because each element is visited and copied exactly once.
Step-by-Step Trace
Consider converting the 1D array {10, 20, 30, 40, 50, 60} into a 2D array with 3 rows and 2 columns using convertTo2D.
| i | oneD[i] | row = i / cols | col = i % cols | twoD[row][col] after assignment |
|---|---|---|---|---|
| 0 | 10 | 0 | 0 | 10 |
| 1 | 20 | 0 | 1 | 20 |
| 2 | 30 | 1 | 0 | 30 |
| 3 | 40 | 1 | 1 | 40 |
| 4 | 50 | 2 | 0 | 50 |
| 5 | 60 | 2 | 1 | 60 |
After processing index i, every element oneD[0..i] has already been written into twoD at row i / cols and column i % cols, so the grid fills up one row at a time in the exact order the source array was read.
Examples
Example 1: Converting a 1D Array into a 3×3 Grid
A 1D array of nine elements can be reshaped into a square 3×3 grid.
int[] oneD = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[][] twoD = convertTo2D(oneD, 3, 3);
// twoD = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Example 2: Flattening a 2×4 Grid Back into a 1D Array
convertTo1D reverses the process, reading the grid row by row.
int[][] grid = {{1, 2, 3, 4}, {5, 6, 7, 8}};
int[] flat = convertTo1D(grid);
// flat = {1, 2, 3, 4, 5, 6, 7, 8}Example 3: A Mismatched Size Throws an Exception
If rows * cols does not equal the source array’s length, convertTo2D fails fast instead of producing a corrupted grid.
int[] oneD = {1, 2, 3, 4, 5};
int[][] twoD = convertTo2D(oneD, 2, 3);
// throws IllegalArgumentException: Array size does not match the target dimensionsCommon Mistakes to Avoid
These are the mistakes that show up most often when developers implement this conversion for the first time.
- Skipping the size check – calling
convertTo2Dwithrows * colsdifferent fromoneD.lengththrows an unrelatedArrayIndexOutOfBoundsExceptiondeep inside the loop instead of a clear error. Validate the sizes before the loop starts. - Swapping the row and column formulas – using
i % colsfor the row andi / colsfor the column silently produces a transposed grid with no exception at all. Double check that the division gives the row and the modulo gives the column. - Assuming every row has the same length when flattening – reading
twoD[0].lengthand reusing it for every row throws an exception, or silently drops elements, the moment the 2D array is jagged. Compute each row’s own length inside the outer loop instead. - Iterating column by column when flattening – nesting the column index as the outer loop reads the grid in column-major order, which produces a 1D array with the elements in the wrong sequence even though no exception is thrown.
Edge Cases to Test
Walk through these inputs before calling the conversion complete.
- Empty 1D array
- Single row (rows = 1)
- Single column (cols = 1)
- rows * cols not equal to the array length
- Jagged 2D array with rows of different lengths
- Null array reference
- Very large dimensions that overflow rows * cols as an int
Additional Considerations
Both conversions run in O(n) time and use O(n) additional space for the new array, since neither method can avoid allocating a destination of the same total size as the source.
True in-place conversion is not possible when the shape changes, because a 1D array and a 2D array are backed by different memory layouts in Java. A 2D array is really an array of row-array references, not one contiguous block, so the best you can do is reuse the same backing values and avoid any copying beyond the one pass each method already performs.
If the source data is jagged, meaning the rows of the 2D array are not all the same length, convertTo1D as written will fail on the second row. A more defensive version should read each row’s own length rather than assuming twoD[0].length applies to every row.
Interview Follow-up Questions
Once you can explain the base conversion, expect an interviewer to push into these variations.
- What if the 2D array is jagged? – sum each row’s individual length first to size the 1D array, instead of multiplying
twoD.lengthbytwoD[0].length. - How would you convert the array using column-major order instead of row-major order? – swap the roles of division and modulo in the index math, so
i % rowsgives the row andi / rowsgives the column. - What if the elements arrive as a stream and you do not know the total count in advance? – buffer values into a growable list until you have collected
colsworth, then emit each completed row and start the next one. - How would you convert a 1D array to 2D using only a fixed, bounded amount of extra memory? – discuss why reshaping without a full-size destination is only possible if the conversion is read lazily, computing
twoD[row][col]on demand from the 1D array rather than materializing the whole grid.
Conclusion
Converting between 1D and 2D arrays comes down to one formula in each direction: row = i / cols and col = i % cols to reshape, and a nested row-then-column walk to flatten. Once that index math is second nature, the rest of the problem is just validation and clean code.
Try adapting the ArrayConverter class to work with String[] or generic arrays, or to support column-major layouts, to make sure the underlying logic has really sunk in. You can learn more about array-based problems in the Arrays category on this site.



