Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Kth largest element

Medium Acceptance 64.92% Points 30.00

Given an array arr[] and a number k. The task is to find the kth largest element in the array.

Examples
Example 1

Example 1

Input: arr[] = [10, 20, 4, 45, 99], k = 2

Output: 45

Explanation: The elements in the array sorted in descending order are: [99, 45, 20, 10, 4]. The 2nd largest element is 45.

Example 2

Example 2

Input: arr[] = [1, 7, 8, 3, 9, 2], k = 4

Output: 3

Explanation: The elements in the array sorted in descending order are: [9, 8, 7, 3, 2, 1]. The 4th largest element is 3.

Hints
Hint 1
Expected Time Complexity: O(n log k)
Hint 2
Expected Auxiliary Space: O(k)
Constraints
  • 1 <= k <= arr.size<= 10^6
  • -106 <= k <= arr.size<= 10^6
Companies
Visa Google Oracle
Topics
Heap
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions