Search code examples
javaarraysperformancematrixspace-complexity

Space complexity of a temp array that is outside a loop


I did come across a famous interview question, in which we are given a 2D array and we need to rotate the array by 90 degrees and while there are many ways to solve it, I decided to make use of an effective approach in which we do something like this.

/*
 * clockwise rotate
 * first reverse up to down, then swap the symmetry 
 * 1 2 3     7 8 9     7 4 1
 * 4 5 6  => 4 5 6  => 8 5 2
 * 7 8 9     1 2 3     9 6 3
*/

My code for above approach is:

public void rotate(int[][] matrix) {
    int s = 0, e = matrix.length - 1;
    while(s < e){
        int[] temp = matrix[s];
        matrix[s] = matrix[e];
        matrix[e] = temp;
        s++; e--;
    }

    for(int i = 0; i < matrix.length; i++){
        for(int j = i+1; j < matrix[i].length; j++){
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }
}

My main concern here is that the array that i'm using inside the first while loop might make the space complexity O(n). What if I simply do this:

int[] temp;
while( s < e ){
   temp = matrix[s];
}

Would now be the space complexity O(1) or will it remain the same?


Solution

  • Your only space outside of the matrix being rotated is a single element and a pointer to a row, each of which is O(1). That the pointer points to something of O(N) space is irrelevant, as it is part of the input.

    Note that you can do the rotation in about 1/2 the time: instead of reflecting the whole matrix two ways, moving each element twice, you can instead rotate each set of 4 elements where A replace B, B replaces C, C replaces D, and D replaces A.