Tutorialspoint
Problem
Solution
Submissions

Kth Largest Element

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to find the kth largest element in an unsorted array. Note that it is the kth largest element in sorted order, not the kth distinct element. You can assume k is always valid, 1 ≤ k ≤ array's length. The algorithm should be efficient and handle large arrays.

Example 1
  • Input: nums = [3,2,1,5,6,4], k = 2
  • Output: 5
  • Explanation:
    • Sort the array in descending order: [6,5,4,3,2,1].
    • The 1st largest element is 6.
    • The 2nd largest element is 5.
    • Therefore, the 2nd largest element is 5.
Example 2
  • Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
  • Output: 4
  • Explanation:
    • Sort the array in descending order: [6,5,5,4,3,3,2,2,1].
    • The 1st largest is 6, 2nd largest is 5, 3rd largest is 5.
    • The 4th largest element is 4.
    • Note that we count duplicates as separate elements.
Constraints
  • 1 ≤ knums.length ≤ 10^5
  • -10^4 ≤ nums[i] ≤ 10^4
  • k is always valid
  • Time Complexity: O(n log k) or O(n) average case
  • Space Complexity: O(k) or O(1)
ArraysGoldman SachsTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a min heap of size k to efficiently find the kth largest element
  • Iterate through the array and maintain only k largest elements in the heap
  • If heap size exceeds k, remove the smallest element from the heap
  • The root of the min heap will be the kth largest element
  • Alternatively, use quickselect algorithm for O(n) average time complexity
  • Another approach is to sort the array and return the element at index (length - k)

Steps to solve by this approach:

 Step 1: Initialize a min heap data structure to store the k largest elements encountered so far.

 Step 2: Implement heap helper functions for maintaining min heap property (heapifyUp and heapifyDown).
 Step 3: Iterate through each element in the input array one by one.
 Step 4: If the heap size is less than k, add the current element to the heap.
 Step 5: If the heap is full and the current element is larger than the heap's minimum, remove the minimum and add the current element.
 Step 6: After processing all elements, the root of the min heap contains the kth largest element.
 Step 7: Return the root element of the min heap as the final result.

Submitted Code :