Complexity of Missing numbers

Suppose that out of the integers from 1 to n n , you are given n 2 n - 2 of them.

What is the order of complexity of finding these 2 missing numbers?

O ( n ) O(\sqrt{n}) O ( e n ) O(e^n) O ( n 2 ) O(n^2) O ( n ) O(n)

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Calvin Lin Staff
Jan 31, 2015

Let the 2 missing numbers be x , y x, y .

O ( n ) O(n) . Find the sum of the n 2 n-2 number.
O ( n ) O(n) . Find the sum of squares of the n 2 n-2 numbers.

O ( 1 ) O(1) .. We know that the sum of the n n numbers is n ( n + 1 ) 2 \frac{ n(n+1) } { 2 } , and the sum of the n n squares is n ( n + 1 ) ( 2 n + 1 ) 6 \frac{ n (n+1)(2n+1) } { 6} .

O ( 1 ) O(1) . We know x + y x + y and x 2 + y 2 x^2 + y^2 by subtracting. We then solve the quadratic to find these 2 numbers.

Hence, we have an O ( n ) O(n) algorithm to find the numbers.

Now, since we need to read all of the input, the minimum time is of the order O ( n ) O(n) .

Thus, the answer is O ( n ) O(n) .

Clearly you can't do better than O ( n ) O(n) ; you need to read the whole input and it takes O ( n ) O(n) time already.

Ivan Koswara - 6 years, 4 months ago

Log in to reply

Right, that was my argument too. However, i'm not always too certain about the most effective algorithm, so I placed the disclaimer. Let me remove it now.

Calvin Lin Staff - 6 years, 4 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...