CodeArchon

easyHeap / Priority QueueAmazonFacebookApple

K-Floor VIP Keeper

A hotel keeps only the K highest-tier guests on its exclusive floor; each new arrival may bump out the lowest-tier VIP.

Design a class that tracks the k-th largest element in a stream. Each `add(val)` returns the current k-th largest.

Choose approach

4
newest
1/24
Narrationstep 1 of 24

Seed value 4. Sift up to maintain min-heap. Current heap size = 1.

1import heapq
2class KthLargest:
3 def __init__(self, k, nums):
4 self.k = k
5 self.heap = []
6 for n in nums: self.add(n)
7 def add(self, val):
8 heapq.heappush(self.heap, val)
9 if len(self.heap) > self.k:
10 heapq.heappop(self.heap)
11 return self.heap[0]
Variables
added=4
size=1
k=3

How to think about it

  1. Only the top K matter. The smallest among those IS the k-th largest.
  2. Min-heap's root is the smallest -> O(1) answer.
  3. On overflow, pop the root. O(log k) per operation.

Edge cases to catch in interview

  • Initial list smaller than k -> heap grows until first k are seen.
  • Repeated values -> treated as multiset.

Examples

Example 1[4,5,5,8,8]
{"k":3,"initial":[4,5,8,2],"stream":[3,5,10,9,4]}

Try your own input

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