MEDIUM NC#64 Heap / Priority Queue

703. Kth Largest Element in a Stream

๐Ÿ“– Problem

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Implement KthLargest class: - KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums. - int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขLevel-order traversal
  • โ€ขQueue discipline
  • โ€ขShortest-step interpretation

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply BFS reasoning pattern
  • โ€ขApply Heap reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use min heap of size k
  • โ†’ Heap always contains k largest elements seen so far
  • โ†’ Top of heap is kth largest element
  • โ†’ When adding new element, push and maintain heap size
  • โ†’ Time: O(n log k) for initialization, O(log k) for add, Space: O(k)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse min heap of size k
  • โ€ขHeap always contains k largest elements seen so far
  • โ€ขTop of heap is kth largest element

Common Pitfalls

  • โ€ขWhen adding new element, push and maintain heap size
  • โ€ขTime: O(n log k) for initialization, O(log k) for add, Space: O(k)

๐Ÿงช Test Cases

Hidden tests on submit: 2

Test Case 1
Not run
Input:
(() => { const kthLargest = new KthLargest(3, [4,5,8,2]); return kthLargest.add(3); })();
Expected:
4
Test Case 2
Not run
Input:
(() => { const kthLargest = new KthLargest(3, [4,5,8,2]); kthLargest.add(3); return kthLargest.add(5); })();
Expected:
5
Test Case 3
Not run
Input:
(() => { const kthLargest = new KthLargest(3, [4,5,8,2]); kthLargest.add(3); kthLargest.add(5); return kthLargest.add(10); })();
Expected:
5

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit