⌘K
Flycodx

Kth Largest Element

Kth Largest Element

MediumSorting100% accepted

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

5 2 3 2 1 5 6

Output

5
  • •1 ≤ n ≤ 10^4, -10^4 ≤ elements ≤ 10^4
solution.py
Loading editor...
Test 1
Test 2
Test 3

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
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3