Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

131. Kth Largest Element in an Array

MediumDay 39 of 60Heap / Priority Queue

Given an integer array nums and an integer k, return the kth largest element. This means the kth largest in sorted order, not the kth distinct value, so duplicates count separately. Try to do better than sorting the whole array.

Example 1
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Sorted descending: 6, 5, 4, 3, 2, 1. The 2nd one 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, ... The 4th one is 4.
Constraints
  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
Hints
Frequently asked at: Meta, Amazon, Microsoft, LinkedIn, Goldman Sachs
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min