All 15 Arrays & Multidimensional Arrays questions
More in Arrays & Multidimensional Arrays
Advertisement
Java › Arrays & Multidimensional Arrays

How would you flatten a 2D array into a 1D array, and conversely, reshape a 1D array into a 2D array?

Intermediate

Answer

Flattening a 2D array involves iterating each row and copying its elements sequentially into a pre-sized 1D destination array (tracking a running offset via System.arraycopy() for efficiency); reshaping a 1D array into 2D requires knowing the desired row/column dimensions in advance and copying corresponding slices of the source array into each newly allocated row -- neither operation has a single built-in JDK utility method, so both are typically implemented manually using System.arraycopy() for performance.
public static int[] flatten(int[][] matrix) {
    int totalLength = Arrays.stream(matrix).mapToInt(row -> row.length).sum();
    int[] result = new int[totalLength];
    int offset = 0;
    for (int[] row : matrix) {
        System.arraycopy(row, 0, result, offset, row.length);
        offset += row.length;
    }
    return result;
}
Real-world example An image-processing routine flattens a 2D pixel grid into a single contiguous 1D array before passing it to a native image-encoding library expecting flat pixel data, using System.arraycopy() per row for efficient bulk copying rather than a slower element-by-element nested loop.

Common follow-ups: What is the time complexity of the flattening operation relative to the total number of elements?;How would you handle flattening a jagged (non-rectangular) 2D array where rows have different lengths?