Microsoft · Question 53 · Heaps
Kth Largest Element in an Array
Problem
Find the kth largest element using a heap.
Approach
Keep a min-heap of size k; its top is the answer.
Time O(nlogk)Space O(k)
How it works
- 1Push every number, evicting past size k.
- 2The heap holds the k largest; top is kth.
Sample input / output
Input: 6 2 3 2 1 5 6 4 Output: 5
Constraints
1 <= k <= nums.length <= 10^5.
Solution — read it, then walk it
Time O(nlogk)Space O(k)Loops 2Branches 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/16
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits