Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to find the k-largest numbers from n unsorted integers with time complexity O(n) and space complexity O(k)?

Tags:

algorithm

I know that we can find the k-largest numbers from n unsorted integers in 2 ways:

  1. Use an algorithm like quick-select to find the Kth largest number, then we can get the k-largest numbers. The time complexity is O(n) and space complexity is O(n)
  2. Use a heap to store the k-largest numbers and iterate through n integers, then add proper integers to the heap. The time complexity is O(nlogk) and space complexity is O(k)

Suppose the n integers are in a stream and we don't have random access to them

I want to know is it possible to find the k-largest numbers from n unsorted integers with time complexity O(n) and space complexity O(k)?

like image 224
lzy9059 Avatar asked Sep 26 '22 23:09

lzy9059


1 Answers

It is. After filling the heap with k elements, instead of evicting one element from the heap after every insertion, evict k elements from the heap after every k insertions. Then you don't need the heap structure any more -- just select every time.

like image 177
David Eisenstat Avatar answered Dec 31 '22 20:12

David Eisenstat