Tutorialspoint
Problem
Solution
Submissions

Kth Largest Element

Certification: Intermediate 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. You must solve it without sorting the entire array.

Example 1
  • Input: nums = [3,2,1,5,6,4], k = 2
  • Output: 5
  • Explanation:
    • The array contains elements [3,2,1,5,6,4].
    • If we sort the array: [1,2,3,4,5,6].
    • The 2nd largest element is 5 (6 is 1st largest, 5 is 2nd largest).
    • Therefore, the answer is 5.
Example 2
  • Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
  • Output: 4
  • Explanation:
    • The array contains elements [3,2,3,1,2,4,5,5,6].
    • If we sort the array: [1,2,2,3,3,4,5,5,6].
    • The 4th largest element is 4 (counting from largest: 6,5,5,4).
    • Therefore, the answer is 4.
Constraints
  • 1 ≤ k ≤ nums.length ≤ 10^5
  • -10^4 ≤ nums[i] ≤ 10^4
  • k is guaranteed to be valid
  • Time Complexity: O(n) average case using quickselect
  • Space Complexity: O(1) for iterative approach
ArraysEYOracle
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 the QuickSelect algorithm, which is based on QuickSort partitioning.
  • Choose a pivot element and partition the array around it.
  • If pivot position equals (n-k), then pivot is the kth largest element.
  • If pivot position is greater than (n-k), search in the left subarray.
  • If pivot position is less than (n-k), search in the right subarray.
  • Continue until you find the element at position (n-k) from the start.

Steps to solve by this approach:

 Step 1: Convert the problem to finding element at position (n-k) in sorted order.

 Step 2: Use quickselect algorithm starting with entire array range.
 Step 3: Choose a pivot element (typically the last element) for partitioning.
 Step 4: Partition array such that elements ≤ pivot are on left, others on right.
 Step 5: Compare pivot position with target position (n-k).
 Step 6: If pivot position equals target, return the pivot element.
 Step 7: Otherwise, recursively search in left or right subarray based on comparison.

Submitted Code :