Problem · Array

Retain Top K Values

Learn this problem
EasyMicrosoftFULLTIMEPHONE SCREEN
See Microsoft hiring insights

Problem statement

Given an integer array nums and an integer k, remove every value except the k largest elements. The relative order of the retained elements must be the same as in the original array.

If there are ties at the cutoff value, keep the earliest tied elements until exactly k elements have been retained.

Function

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

Examples

Example 1

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

The three largest elements are 5, 5, and 3. They are returned in their original order.

Example 2

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

When equal values cross the cutoff, keep the earliest occurrences needed to return exactly k elements.

Constraints

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • 0 <= k <= nums.length
  • The return value must contain exactly k elements.
  • The relative order of retained elements must match their order in the original array.
  • When multiple elements share the cutoff value, keep the earliest-occurring tied elements until exactly k elements have been retained.

More Microsoft problems

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