Skip to main content

Kth Largest Element in a Stream

Design a class to find the kth largest element in a stream. Think about: How to efficiently maintain the kth largest? Hint: Use a min-heap of size k. Example: KthLargest(3, [4, 5, 8, 2]) add(3) → 4 add(5) → 5 add(10) → 5

Kth Largest Element in a Stream is about always pulling the next best option efficiently as the data changes. It's a great warm-up that builds priority-based reasoning without a ton of moving parts. If your heap represents best candidates right now, the rest falls into place.

Examples

You write

KthLargest: add(val: int)

  1. Example 1

    Input
    KthLargest(3, [4,5,8,2]), add(3) => 4, add(5) => 5, add(10) => 5, add(9) => 8, add(4) => 8
    returns
    [4, 5, 5, 8, 8]
  2. Example 2

    Input
    KthLargest(1, []), add(3) => 3, add(5) => 5, add(10) => 10
    returns
    [3, 5, 10]

The pattern behind it

Trees

I reach for it when

  • Each node has children, and the answer depends on the subtrees.
  • The statement says depth, height, ancestor or path.

Say this before you type. Say what a call returns for an empty tree, and what it returns for a node.

All 22 Trees problems

Heaps

I reach for it when

  • You need the k largest or k smallest items.
  • You repeatedly take the best remaining item.

Say this before you type. Say what the heap holds, how big it stays, and what sits on top.

All 22 Heaps problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Kth Largest Element in a Streameasy