Facebook PixelKth Largest Element in an Array — Coding Practice
Kth Largest Element in an ArrayMedium

Kth Largest Element in an Array

Medium 16.4k67% acceptance
ArrayHeapDivide and ConquerQuickselect

Given an integer array nums and an integer k, return the kth largest element in the array (1-indexed).

This is the kth element in sorted (descending) order — note it is the kth largest distinct position, not the kth distinct value, so duplicates count.

Example 1
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Sorted descending: [6,5,4,3,2,1]. The 2nd largest is 5.
Example 2
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
Sorted descending: [6,5,5,4,3,3,2,2,1]. The 4th element is 4 (duplicates are kept).
Example 3
Input: nums = [1], k = 1
Output: 1
Constraints
  • 1 ≤ k ≤ nums.length ≤ 100000
  • -10000 ≤ nums[i] ≤ 10000
Asked atAmazonMetaGoogleMicrosoftApple
JavaScript
Loading editor…
Case 1
[3,2,1,5,6,4], 2
expected: 5
Case 2
[3,2,3,1,2,4,5,5,6], 4
expected: 4
Case 3
[1], 1
expected: 1
Case 4
[2,1], 2
expected: 1
Case 5
[7,7,7,7], 3
expected: 7
Case 6
[-1,-1,0,1], 1
expected: 1
Case 7
[5,3,8,1,9,2], 6
expected: 1