DevPath

← All problems

Kth Largest Element

Medium heap · sorting

Description

Return the kth largest element in the array (1-based, counting duplicates).

Constraints

1 <= k <= n <= 100000

Examples

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

Output: 5

Hints (1)
  • A min-heap of size k, or a sort, both work.

Solutions

Sort descending. (requires "sort") · Time O(n log n) · Space O(1)

func findKthLargest(nums []int, k int) int {
    sort.Sort(sort.Reverse(sort.IntSlice(nums)))
    return nums[k-1]
}

Create a free account to submit solutions, track progress and save problems.

Create account