Skip to content
Advertisement

What is the time complexity of the following piece of code

int FindSum(int[] A, int[] B){
    int[] temp = A;
    A = B;
    B = temp;
}

here in this java code we are swapping both the arrays, in this case only the memory reference of arrays is changing or there is swapping of elements between A and B? What would be the time complexity O(1) or O(m+n) where m and n are sizes of arrays A and B respectively. This piece of code was found on leetcode https://leetcode.com/articles/median-of-two-sorted-arrays/

Advertisement

Answer

This code is O(1). As a side note, it does nothing.

They are not primitives, so they are only trading references. Also, the local variables A and B, when changed, do not reflect a change in whatever method called them. The only way to swap the actual values of A and/or B in main is to change them by reference in the arrays passed, but swapping the locations of the references does nothing.

Advertisement