MediumArrayDivide and ConquerSortingHeap (Priority Queue)Quickselect

Kth Largest Element in an Array

LeetCode
1 approach, code in all languages

You are given an integer array `nums` and an integer `k`.

Return the `k`-th largest element in the array. Note that this is the `k`-th largest element in sorted order, not the `k`-th distinct element — duplicate values each count toward the ranking.

Aim to solve it without fully sorting the array.

Example 1

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

Output: 5

Sorted in descending order the array is [6,5,4,3,2,1], so the 2nd largest value is 5.

Example 2

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

Output: 4

Sorted descending it is [6,5,5,4,3,3,2,2,1]; the 4th entry is 4.

Constraints

  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now