GATE CSE
First time here? Checkout the FAQ!
x
+2 votes
385 views
In a min-heap with n elements

1).  The 7th smallest element can be found in time, if duplicates are allowed ?

2).  The 7th distinct smallest element can be found in time, If duplicates are allowed ?
asked in Algorithms by Veteran (47.2k points)   | 385 views
O(n)  for both.
For 2nd one , O(n) is right, as we have to use hashtable .

For 1st, O(lgn) is given . I think it should be O(1) .
Ohh ... yes ... if we have elements like - 1,2 ,3,3,4,4,5,5,5,6,6,6,7

And ans for 1st is 5 and for 2nd it is 7 then you are correct...
1) O(1), because we can do it in constant time

2) O(N) counting sort will be applied
I agree the operation concerned is find() , which takes O(1) if duplicates are allowed but if asked for distinct 7th minimum and duplicates are allowed we may need to do find() operation for entire tree which will take O(n) time

2 Answers

0 votes

It will take O(1)

    

 

answered by Active (2.2k points)  
I think same here

but for 1st one, answer is given O(lg N).
0 votes
For first one :

O(log n)

Reason : To delete an element , it takes O(1), then we have to heapify , which takes O(log n);

Now for 7th smallest element, we need 7 such operations, hence O(7 log n) = O(log n)

For 2nd one :

O(n)
answered by Loyal (3.8k points)  
good algorithm!!

i wasn't aware of such a solution. thanks!!

@kapilp

are you sure for first one it is O(logn)

If we will go with simple procedure like 1+2+3+....2^n-1 comaprison to find nth smallest element then it is O(1)

another one is start deleting the element till kth level to reach the kth smallest element which is O(logn)

because everywhere I am seeing O(1) as well O(logn) time...can u plz confirm?? even I am bit confuse

see this:

http://gateoverflow.in/5915/complexity-finding-smallest-element-already-constructed

http://stackoverflow.com/questions/21600312/searching-the-7th-largest-element-in-a-max-heap

 

@cse23, yes, it is O(1).

and for 2nd it is O(N).
ok fine...so to find kth smallest element from the min heap..we can do in O(1) time.
yes..


Top Users May 2017
  1. akash.dinkar12

    3302 Points

  2. pawan kumarln

    1776 Points

  3. Bikram

    1646 Points

  4. sh!va

    1640 Points

  5. Arjun

    1396 Points

  6. Devshree Dubey

    1272 Points

  7. Debashish Deka

    1142 Points

  8. Angkit

    1044 Points

  9. LeenSharma

    1000 Points

  10. Arunav Khare

    754 Points

Monthly Topper: Rs. 500 gift card
Top Users 2017 May 22 - 28
  1. Bikram

    732 Points

  2. Arnab Bhadra

    402 Points

  3. pawan kumarln

    402 Points

  4. bharti

    304 Points

  5. LeenSharma

    238 Points


22,823 questions
29,142 answers
65,209 comments
27,666 users