简体   繁体   中英

Why does this piece of code with two for-loops not have Big O runtime of O(N^2)?

I am learning Big O notation in my algorithms class. I just done an online quiz for this week where we get a bunch of code blocks which we have to select the big O complexity for.

I got everything correct except this code block:

void printPairs(int[] arrX, int[] arrY) {
    for(int i = 0; i < arrX.length; i++) {
        for(int j = 0; j < arrY.length; j++) {
            System.out.println(arrX[i] + "," + arrY[j]);
        }
    }
}

I put in O(N^2) but I got it wrong which I am not sure why, there are two for-loops? And unfortunately I can not see the other options available or correct answer till the end of the week.

The runtime would be O(N²) if there was only one input ie one array passed as a parameter and iterated over in each of the two for-loops.

Because there are two inputs ( arrX and arrY ) for the method and both are used in each of the two for-loops.

The Big O runtime is O(XY) where X = arrX.length and Y = arrY.length .

Edit: As stated by @Oighea This is still a quadratic-time algorithm. It is just in two variables.

Think about the amount of elements per array, let's say arrX has n elements and arrY has m elements. The first iteration is done over arrX , so regarding only the first loop would have a runtime of O(n) . The inner loop iterating over arrY , which has m elements has a runtime of O(m) , due to it being iterated once for every element of arrX , the entire method has a worst case runtime of O(nm) . Assuming the case of both arrays having the same length, that special case would have a runtime of O(nm) with n = m and that would make it O(n^2) .

Your answer is not totally wrong, but it does not include all possibilities, just one...

Yes, you are right. There ARE 2 loops. but each of the loop iterate over different arrays.

So if the length of the first array is= N and that if the second array is = M , then the worst case time complexity will be O(nm)

Now, if the size of both the arrays is same, n=m, then O(nm ) =O(n^2 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM