in DS recategorized by
3,968 views
8 votes
8 votes
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 ?
in DS recategorized by
by
4.0k views

9 Comments

O(n)  for both.
1
1
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) .
0
0
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
1
1) O(1), because we can do it in constant time

2) O(N) counting sort will be applied
2
2
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
0
0
@srestha how can you apply counting sort on this bcoz  he mentioned heap right  ?
0
0
In the question what do we mean by term "distinct" ?
0
0

duplicates are not allowed, What will be the answer if we were asked to find the

  1. $\\ (n-7)^{th} \\ $ smallest element
  2. $\\ \frac{n}{7}^{th}\\$ smallest element

 

0
0
  1. $\Theta (1)$
  2. $O(n)$

If elements are repeated, then also this holds true. Consider the heap array
1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 4 5 6 7

The given procedure returns 1 and that is the correct answer. “7" must be returned only if the questions asks "7th" distinct smallest element which might require entire scanning of the heap and needs a hashtable to be run in $O(n)$ time

Source: Arjun sir comment

0
0

3 Answers

1 vote
1 vote
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)

4 Comments

ok fine...so to find kth smallest element from the min heap..we can do in O(1) time.
0
0
yes..
0
0
Here you are taking 7 as a Constant. What if it's nth smallest?  Will it be n * log n??
0
0
0 votes
0 votes

It will take O(1)

    

1 comment

I think same here

but for 1st one, answer is given O(lg N).
0
0
0 votes
0 votes
for first question it is O(log n) deletion in a min heap also does heapify  after deletion  so it is O(log n) ...correct me if i am wrong

Related questions

1 vote
1 vote
1 answer
1