FastPrepTop K Largest Values with a Heap
Problems/Top K Largest Values with a Heap

Top K Largest Values with a Heap

Meta logoMeta● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report names a top-k heap exercise. The conventional largest-values contract, including duplicate occurrences, matches the visible source at about 85%.

Given an integer array nums and an integer k, return the k largest occurrences in nonincreasing order. Preserve duplicate occurrences.

Process the array with a min-heap containing at most k values, then order the selected values for the returned result. Return an empty array when k is zero.

Function

topKLargest(nums: int[], k: int) → int[]

Examples

Example 1

nums = [3,2,1,5,6,4]k = 2return = [6,5]

The size-two heap retains 5 and 6.

Example 2

nums = [4,1,4,2,4]k = 3return = [4,4,4]

Duplicate occurrences remain separate selected values.

Example 3

nums = [-5,-1,-3]k = 0return = []

Selecting zero values returns an empty result.

Constraints

  • 0 <= nums.length <= 200000.
  • -10^9 <= nums[i] <= 10^9.
  • 0 <= k <= nums.length.

More Meta problems

  • Count Events in Rolling Minute WindowsPHONE SCREEN · Seen Oct 2026
  • Valid Word AbbreviationPHONE SCREEN · Seen Oct 2026
  • Shortest Path in a Binary MatrixPHONE SCREEN · Seen Sep 2026
All Meta interview questionsSee Meta hiring insights
Saved
class Solution {
    public int[] topKLargest(int[] nums, int k) {
        // Write your code here.
    }

}
Checking account…