FastPrepKth Largest Element without a Heap

Kth Largest Element without a Heap

ByteDance logoByteDance● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given integer array nums and one-indexed rank k, return its kth largest element. Duplicate values occupy separate ranks, as in descending sorted order.

Do not use a heap. For this exercise, implement a selection method without fully sorting the input, using the bounded portable interface below.

Function

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

Examples

Example 1

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

The two largest elements are 6 and 5.

Example 2

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

The descending sequence starts 6, 5, 5, 4; duplicates keep separate positions.

Constraints

  • 1 <= nums.length <= 2000.
  • 1 <= k <= nums.length.
  • -10^6 <= nums[i] <= 10^6.

More ByteDance problems

See ByteDance hiring insights
public int kthLargest(int[] nums, int k) {
    // Write your code here.
}
nums[3,2,1,5,6,4]
k2
expected5
Checking account…