Problem · Array

K Largest Integers in Descending Order

Learn this problem
MediumJPMorgan Chase logoJPMorgan ChaseFULLTIMEONSITE INTERVIEW

Problem statement

You are given an integer array nums and an integer k. Return the k largest occurrences in nums, sorted in nonincreasing order.

Duplicate occurrences are retained. For example, if the largest value appears three times and k = 3, all three copies belong in the result.

Function

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

Examples

Example 1

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

The two largest occurrences are 6 and 5, returned from largest to smallest.

Example 2

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

Each occurrence counts independently, so all three copies of 4 are retained.

Example 3

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

When k is zero, the result is empty.

Constraints

  • 0 <= nums.length <= 200000.
  • -10^9 <= nums[i] <= 10^9.
  • 0 <= k <= nums.length.
  • The result must contain exactly k values in nonincreasing order.

More JPMorgan Chase problems

drafts saved locally
public int[] kLargestIntegers(int[] nums, int k) {
  // write your code here
}
nums[3,2,1,5,6,4]
k2
expected[6,5]
checking account