FastPrepFastPrep
Problem Brief

Top-K Using a Priority Queue

FULLTIMEONSITE INTERVIEW
See Uber online assessment and hiring insights

Given an integer array nums and an integer k, return the largest k elements from the array in any order.

An O(n log k) solution is expected.

Function Description

Complete the function topKUsingPriorityQueue in the editor below.

topKUsingPriorityQueue has the following parameters:

  1. int[] nums: the input array
  2. int k: the number of largest elements to return

Returns

int[]: any ordering of the largest k values.

1Example 1

Input
nums = [3, 2, 1, 5, 6, 4], k = 2
Output
[5, 6]
Explanation

The two largest values are 5 and 6. Any order is acceptable.

Constraints

Limits and guarantees your solution can rely on.

  • 1 <= nums.length <= 2 * 10^5
  • -10^9 <= nums[i] <= 10^9
  • 1 <= k <= nums.length
public int[] topKUsingPriorityQueue(int[] nums, int k) {
    // write your code here
}
Input

nums

[3, 2, 1, 5, 6, 4]

k

2

Output

[5, 6]

Sign in to submit your solution.