Algorithms and Data Structures · Middle · Question 11 of 75

How do you find the k largest elements of a large array efficiently?

Explanation

The heap always holds the k largest seen so far, and its root is the smallest of them. The total cost is O(n log k), which beats sorting (O(n log n)) when k is small, and works on streams too.

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 11

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz