2

Given an array A, the task is to find the largest, 2nd largest, 4th largest, 8th largest, 16th largest, ... and so on up to 2^logn largest element. Give an O(n) algorithm to do this.

I do understand that elements need not to be sorted between the selected largest elements (for example between 4th and 8th largest). I also thought about using the kth largest elements algorithm but that would only save me sorting a small (largest) fraction of the array that is between 2^logn and max(n) and it's not even O(n).

I also thought about bucket sorting by splinting exponentially (instead of evenly) but this would still not provide me with the complexity guarantees that are required.

gonidelis
  • 885
  • 10
  • 32

1 Answers1

3

If we assume quickselect (or some variant thereof) is O(n), then if we start at the 2^lognth element, then extract all values that are less than it, then run the next query on those, etc., we would be halving n for our purpose each time. This would result in O(n + n/2 + n/4 + n/8...) = O(n).

גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61