Tutorialspoint
Problem
Solution
Submissions

Kth Largest Element in an Array

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

Write a C# program to find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Implement the FindKthLargest(int[] nums, int k) function.

Example 1
  • Input: nums = [3,2,1,5,6,4], k = 2
  • Output: 5
  • Explanation:
    • Step 1: Sort the array [1,2,3,4,5,6]
    • Step 2: The 2nd largest element is 5
Example 2
  • Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
  • Output: 4
  • Explanation:
    • Step 1: Sort the array [1,2,2,3,3,4,5,5,6]
    • Step 2: The 4th largest element is 4
Constraints
  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • Time Complexity: O(n) average case, O(n²) worst case
  • Space Complexity: O(1)
ArraysMicrosoftWalmart
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

  • While sorting the array works (O(n log n)), there are more efficient approaches
  • Consider using the Quick Select algorithm, which is based on Quick Sort
  • Alternatively, a min-heap of size k can be used
  • Focus on partitioning the array and only recursing on the side that contains the kth largest element
  • Remember that the kth largest is at index n-k in a sorted array

Steps to solve by this approach:

 Step 1: Convert the kth largest to (n-k)th smallest index for easier implementation
 Step 2: Implement QuickSelect algorithm similar to QuickSort but only recursing on one side
 Step 3: Randomly select a pivot element to avoid worst-case performance
 Step 4: Partition the array around the pivot value, moving smaller elements to the left
 Step 5: Check if the pivot's final position matches our target index
 Step 6: If it matches, return the value; if pivot is smaller, search right subarray; otherwise search left
 Step 7: Continue recursively until we find the kth largest element

Submitted Code :