Search code examples
javaarraysmultidimensional-arraymergeconcatenation

How to combine a 2D array into one, using a pre-defined method that only takes 2 arrays at a time?


I'm working on an interview practice question where we're given a 2d array (arr[16][64], so 16 arrays with 64 elements each). We're first asked to sort each array, and then combine them into one big sorted array, using the given methods (without creating any new methods).

The given method for combining takes only two arrays, merges them, and returns a single combined array. It's a very straightforward function, no libraries or anything like that, just plain Java code.

I was able to sort the 16 arrays, but I can't figure out how to use the given combine() function to merge/combine all 16 arrays. The only thing I could think to do was

    for (int i = 0; i < 16; i++) {
        finalArray = combine(2dArray[i], 2dArray[i+1]);
    }

but of course that's only combining 2 arrays. Where should I go from here?


Solution

  • As per your problem statement the following should work:

    int[] finalArray = new int[0];
    for (int i = 0; i < 16; i++) {
        finalArray = combine(finalArray, 2dArray[i]);
    }
    return finalArray;
    

    The invariant for this loop is that finalArray is always sorted. So, at the end you will have one big sorted array in this variable.

    P.S. Using the OP's original 2dArray variable name in the code snippet. However, it's not a valid name in Java because you can't start a variable name with a number.