Leetcode #703: Kth Largest Element in a Stream
In this guide, we solve Leetcode #703 Kth Largest Element in a Stream in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are part of a university admissions office and need to keep track of the kth highest test score from applicants in real-time. This helps to determine cut-off marks for interviews and admissions dynamically as new applicants submit their scores.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Tree, Design, Binary Search Tree, Binary Tree, Data Stream, Heap (Priority Queue)
Intuition
We need to repeatedly access the smallest or largest element as the input changes.
A heap provides fast insertions and removals while keeping order.
Approach
Push candidates into the heap as you scan, and pop when you need the best element.
Keep the heap size bounded if the problem requires a top-k structure.
Steps:
- Push candidates into a heap.
- Pop the best candidate when needed.
- Maintain heap size or invariants.
Python Solution
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.min_q = []
for x in nums:
self.add(x)
def add(self, val: int) -> int:
heappush(self.min_q, val)
if len(self.min_q) > self.k:
heappop(self.min_q)
return self.min_q[0]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
Complexity
The time complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.