Kth Largest Element
Kth Largest Element
Given an unsorted integer array of n elements and a positive integer k, find and print the kth largest element. The kth largest means the element that would be at position k when the array is sorted in descending order (1-indexed, so the 1st largest is the maximum). Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer.
Input format — only if your code reads from stdin
Input format (stdin): - First line: two integers n (array size) and k - Second line: n space-separated integers Output: the kth largest element as a single integer. Note: k is guaranteed to be a valid index (1 ≤ k ≤ n).
Approach
Simple approach: sort in descending order and return index k-1. Optimal approach: maintain a min-heap of size k — iterate all elements, pushing to the heap and popping when it exceeds size k. The heap root is the answer.
Input
Output
- •
1 ≤ n ≤ 10^4, -10^4 ≤ elements ≤ 10^4
More Sorting problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards