InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Heap & Priority Queue

Kth Largest Element in an Array

medium Original ↗ 00:00

Problem

Given an integer array nums and an integer k, return the k-th largest element in sorted order, counting duplicates — not the k-th distinct value.

Follow-up: can you solve it without fully sorting the array?

Examples

  • nums = [3, 2, 1, 5, 6, 4], k = 25 — sorted descending: 6, 5, 4, 3, 2, 1.
  • nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 44 — sorted descending: 6, 5, 5, 4, … (each 5 takes its own rank).
  • nums = [1], k = 11 — the only element is the 1st largest.

Constraints

  • 1 <= k <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4

Think about it first

Hint 1 Sorting solves it in one line at O(n log n). The point of the follow-up is that you were asked for one element, not a full ordering.
Hint 2 Sweep the array once, keeping only the k largest values seen so far in a min-heap; its root is the current k-th largest. What does each element cost, and when does this beat sorting? Also compare the value range against n.
Hint 3 Two O(n)-flavored routes: quickselect (partition around a pivot, recurse into the side holding index n−k) for average O(n), or counting sort over the 2·10^4-wide value range — count occurrences, then walk from the top subtracting counts until k is used up.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug