File: kth-largest-element-in-a-stream/solution.py

Date: 2026-06-06

Time: 17:12

Purpose

This file implements LeetCode 703 — Kth Largest Element in a Stream. It provides a KthLargest class that maintains a running stream of integers and can answer "what is the kth largest element right now?" in O(log k) time per insertion. It's a textbook application of a bounded min-heap.

Key Components

KthLargest class

Constructor _init_(self, k: int, nums: list[int]) -> None

Method add(self, val: int) -> int

Patterns

Bounded min-heap — the central insight. Instead of sorting or maintaining all elements, keep only the top k in a min-heap. The heap root is always the answer. This is the canonical approach for "kth largest in a stream" problems and generalizes to any top-k tracking scenario.

Defensive copynums[:] on line 12 avoids mutating the caller's list when heapify rearranges it in-place.

Dependencies

Imports: heapq from the standard library — provides heapify, heappush, heappop.

Imported by: kth-largest-element-in-a-stream/test_solution.py directly. The massive "Imported By" list in the prompt is an artifact of the test harness — those test files all share a common import pattern, not a direct dependency on this solution.

Flow

1. Init: nums → copy → heapify (O(n)) → pop down to size k (O((n-k) log n))

2. Add: push val (O(log k)) → conditional pop (O(log k)) → return root (O(1))

Total init cost: O(n log n) worst case. Each add: O(log k). Space: O(k).

Invariants

Error Handling

None. The code trusts its inputs: k >= 1, nums is a valid list, and add is called with an integer. Calling add before k elements exist will still work — self.heap[0] returns the minimum of whatever's present, which is correct for the LeetCode contract (the problem guarantees at least k elements exist when add is called).

Topics to Explore

Beliefs