Skip to main content
Data Structures & Algorithms Intermediate Practical Coding Topic: Heaps & Sliding Window

Compare Sliding Window and Heap patterns for O(n log k) stream top-K problems

Quick Summary: Finding the K largest items via full sorting takes O(n log n) time and O(n) memory, whereas maintaining a Min-Heap capped strictly at size K processes unbounded streams in O(n log k) time and O(k) memory.

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last verified:

Direct Interview Answer

When K is much smaller than N (such as top 10 trends out of 10 million events), storing only the K largest candidates in a Min-Heap lets us discard any incoming element smaller than heap[0] immediately in O(1).

Detailed Technical Explanation

In Python, heapq is strictly a min-heap (ideal directly for tracking K largest!). If you ever need a max-heap in Python, push negated tuples (-priority, seq_id, payload) where a monotonic tie-breaker avoids TypeError on equal priorities.

Practical Walkthrough

Finding the K-th largest element in an incoming Python stream using O(k) space.

Code Example — PYTHON
import heapq

def kth_largest(nums: list[int], k: int) -> int:
    min_heap: list[int] = []
    for n in nums:
        heapq.heappush(min_heap, n)
        if len(min_heap) > k:
            heapq.heappop(min_heap)
    return min_heap[0]

print(kth_largest([3, 2, 1, 5, 6, 4], 2))
Expected Output / Verification
5

Real-World Production Use Case

Streaming latency percentile trackers, top-K search trend boards, and K-way log merge engines.

Common Interview Mistakes to Avoid

  • Calling heapq.heappush on every item without popping when len > k, wasting O(n) space.
  • Using Python list.pop(0) during BFS queues (O(n) shift) instead of collections.deque().popleft() (O(1)).
Topics: #dsa #heap #priority-queue #python #sliding-window
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.