Tutorialspoint
Problem
Solution
Submissions

Kth Largest Element .

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 15

Write a Python program that finds the kth largest element in a given list using the Quickselect algorithm.

Example 1
  • Input: [3, 2, 1, 5, 6, 4]
  • k: 2
  • Output: 5
  • Explanation:
    • Step 1: Use the Quickselect algorithm to find the kth largest element.
    • Step 2: Choose a pivot element and partition the array around it.
    • Step 3: Depending on the position of the pivot, either search in the left or right partition.
    • Step 4: Continue this process until we find the kth largest element.
    • Step 5: In this example, the 2nd largest element is 5.
Example 2
  • Input: [1, 2, 3, 4, 5]
  • k: 1
  • Output: 5
  • Explanation:
    • Step 1: Use the Quickselect algorithm by choosing pivots and partitioning.
    • Step 2: For simplicity, we can choose the first element as the pivot.
    • Step 3: After partitioning, determine which side contains the kth largest element.
    • Step 4: Continue the process on the selected partition until the pivot is at the correct position.
    • Step 5: The 1st largest element is 5.
Constraints
  • 1 ≤ len(nums) ≤ 10^4
  • 1 ≤ k ≤ len(nums)
  • -10^4 ≤ nums[i] ≤ 10^4
  • Time Complexity: O(n) on average, O(n²) in the worst case
  • Space Complexity: O(1)
RecursionAlgorithmsCognizantAccenture
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 a variation of the Quicksort algorithm.
  • Partition the array and recursively select the kth largest element.
  • Handle edge cases where the list is empty or k is out of bounds.

Steps to solve by this approach:

 Step 1: Implement the Quickselect algorithm, a variation of Quicksort.
 Step 2: Select a pivot element and partition the array around it.
 Step 3: If pivot index equals target index (n-k), return the pivot element.
 Step 4: If pivot index is greater than target index, recur for the left subarray.
 Step 5: If pivot index is less than target index, recur for the right subarray.
 Step 6: Continue until the kth largest element is found.

Submitted Code :