00:00

Problem Statement

Input/Output Examples

Visual Explanation

The heap never holds more than k + 1 values, so each insertion costs O(log k) instead of O(log n).

Approaches

The heap is simple and works on streams. Quickselect is faster on average for a single array.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the array length. The heap processes every value with O(log k) work; quickselect averages O(n) but can degrade with unlucky pivots.

Interview Tips and Recommended Approach

  • Use a min-heap for the k largest. A max-heap of all values works too but uses O(n) memory.
  • Count duplicates unless the question asks for distinct values.
  • Explain quickselect's worst case and how random pivots avoid it in practice.
  • Mention sorting as the O(n log n) baseline.

Recommended Approach: Min-Heap of Size k

Why: it is short, hard to get wrong, uses little memory and also works on data streams.