Search code examples
arraysperformancememory

Interview Question: Replacing two arrays' place in memory


Given two consecutive arrays, A and B. They look something like

int AandB[] = {a1,a2,...,am,b1,b2,...,bn};

You need to write a program that would switch the order of arrays A and B in the memory, so that B would appear before A. In our example, AandB should become

int AandB[] = {b1,b2,...,bn,a1,...,am};

What's the most efficient way to do that?


Solution

  • Three array reverses:

    (a1 a2 a3 a4 a5 b1 b2 b3)
     b3 b2 b1 a5 a4 a3 a2 a1
    (b3 b2 b1)a5 a4 a3 a2 a1
     b1 b2 b3 a5 a4 a3 a2 a1
     b1 b2 b3(a5 a4 a3 a2 a1)
     b1 b2 b3 a1 a2 a3 a4 a5
    

    Expressed using a "rev" function that takes a start and end:

    rev(AandB, 0, n+m)
    rev(AandB, 0, m)
    rev(AandB, m, n)
    

    For rev (omitting types, etc. for clarity):

    rev(x, i, j) {
        j--; // j points to one after the subarray we're reversing
        while (i < j) {
            tmp = x[i];
            x[i] = x[j];
            x[j] = tmp;
            i++;
            j--;
        }
    }