CodeArchon

mediumHeap / Priority QueueAmazonFacebookLinkedIn

Rank Rail Selector

A trading desk ranks instrument scores and only cares about the K highest; smaller noise is discarded on the fly.

Given an integer array nums and integer k, return the k-th largest element in the array.

Choose approach

3
new
1/11
Narrationstep 1 of 11

Push 3. Heap size = 1.

1import heapq
2def findKthLargest(nums, k):
3 h = []
4 for n in nums:
5 heapq.heappush(h, n)
6 if len(h) > k: heapq.heappop(h)
7 return h[0]
Variables
pushed=3
size=1
k=2

How to think about it

  1. Keeping only the top K candidates saves memory on huge arrays.
  2. Smallest-of-top-K is exactly the k-th largest.
  3. Quickselect gives O(n) average but worst-case O(n²); heap is more predictable.

Edge cases to catch in interview

  • k = 1 -> global maximum.
  • k = n -> global minimum.

Examples

Example 15
{"nums":[3,2,1,5,6,4],"k":2}
Example 24
{"nums":[3,2,3,1,2,4,5,5,6],"k":4}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed