← PayPal bank

PayPal · Question 69 · Heaps

Kth Largest Element in an Array

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

Problem

Find the kth largest element in an unsorted array.

Approach

Use a min-heap (priority queue) of size k.

Time O(nlogk)Space O(k)

How it works

  1. 1Keep only the k largest in the heap.
  2. 2Its top is the kth largest.

Sample input / output

Input:
nums = [3, 2, 1, 5, 6, 4], k = 2
Output:
5

Constraints

1 <= k <= nums.length <= 10^5.

Solution — read it, then walk it

Time O(nlogk)Space O(k)Loops 1Branches 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> pq =new PriorityQueue<>()for (int num : nums)pq.offer(num)if (pq.size() > k)pq.poll()RETURN pq.peek()DEFINE static voidmain(String[] args)System.out.println(findKthLargest(newint[]{3, 2, 1, 5, 6, 4},2))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/12

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