← Microsoft bank

Microsoft · Question 53 · Heaps

Kth Largest Element in an Array

HeapsJavacode⏱ O(nlogk)💾 O(k)
Product-based

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

  1. 1Push every number, evicting past size k.
  2. 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.
yes↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intfindKthLargest(int[] nums,int k)PriorityQueue<Integer>minHeap = newPriorityQueue<>()for (int num : nums)minHeap.offer(num)if (minHeap.size() >k)minHeap.poll()RETURN minHeap.peek()DEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE n = sc.nextInt();int k = sc.nextInt()DEFINE [] nums = new int[n]for (int i = 0; i <nums.length; i++)nums[i] = sc.nextInt()System.out.println(findKthLargest(nums,k))END
  • 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