in Algorithms edited by
1,438 views
5 votes
5 votes
There are n distinct numbers are given not in sorted order. How much time it will take to select a number say k which is neither k-th minimum nor k-th maximum.

A. O$(n)$

B. O$(1)$

C. O$(k)$

D. O$(k\log k)$.
in Algorithms edited by
by
1.4k views

4 Comments

can u plz explain k-th min and k-th max means. i'm nt getting.
0
0
take k = 3,

then the choosen element should not be 3rd min and max,

but it can be 1st/2nd min and max .
0
0
edited by
O(k) I think.
0
0

1 Answer

2 votes
2 votes

For this algorithm we have two cases$\Rightarrow$

case 1$\Rightarrow$when k$\geq$n

example$\Rightarrow ar\left [ 5 \right ]=\left \{ 5,4,3,2,1 \right \}$

Let $P\left ( x \right )=$Neither 5th Maximum nor 5th minimum .

$\Rightarrow$$\exists {\left ( P\left ( x \right )\right )}'$$\Rightarrow \Theta \left ( 1 \right )$

case 2:when k$< n$

step 1$\Rightarrow$Choose any subset of size $2k+1$

step 2$\Rightarrow$sort the Array $\Rightarrow \Theta \left ( k\log k \right )$

step 3$\Rightarrow$find the median ,it will be neither kth maximum nor kth minimum 

time complexity $T\left ( n \right )= k\log k$

example-:

https://gateoverflow.in/8113/gate2015-2_22 here k$< n$

so median can be found in $\Theta \left ( k \right )$

$T\left ( n \right )=\Theta \left ( k+k\log k \right )= \Theta \left ( k\log k \right )$

edited by

4 Comments

yes in the first case check if k>n,then simply return.i.e no such element exists which is neither kth maximum nor kth minimum
0
0

@sourav anand

If you take any 2k + 1 elements and find its median, then itself it is neither the kth minimum nor maximum .

Finding median gives O(K) which is more optimal than sorting O(k lg k).

But, there are some drawbacks as it only good for 2k + 1 < N , what if 2k + 1 > N.

Then , finding median gives O(K) still, but actually it now covers the whole array , so it becomes O(N).

Hence, the question has 2 cases and some additional information must be given regarding this.

1
1
No, now you have the complete input N , and finding a median in this is O(N).
0
0