Saturday, February 21, 2009

find the k largest or smallest numbers from a set of n numbers

3. How do you find the k largest or smallest numbers from a set of n numbers

Solution:

Build a min/max heap of size K from the available set.

Time complexity: n Log K

3 comments:

Varunkumar Nagarajan said...

In fact, we can achieve it by any using any height balanced tree and do an in-order traversal for K elements. Again, it takes O(n log n).

Also, I think even using heap tree, time complexity will be O(n log n) not O(n log k). Its because, we need to scan the entire list and insert into heap and adjust. This takes O(n log n) -- right??

rogue said...

It would be O(n log k) because we should maintain a heap of size k.

Inserting an element into this heap will be O(log k).

This has to be done (worse case) for n elements. so O(n log k).

Varunkumar Nagarajan said...

Yeah, Got it. Thanks!