Skip to content
Learn Netverks

Lesson

Step 27/36 75% through track

heaps-priority-queue

Heaps and priority queues

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Heaps and priority queues: data structure and algorithm concepts with complexity analysis and interview-ready C++ examples.

Hierarchical and priority data drives search, scheduling, and streaming aggregates.

You will apply Heaps and priority queues in contexts like: File systems, DOM-like hierarchies, schedulers, and top-K dashboards.

Compile and run C++17 snippets in the playground (`int main`, `std::cout`); after each run, state time and space complexity before moving on.

When you can explain the previous lesson's ideas in your own words.

A binary heap is a complete tree stored in an array where parent ≤ children (min-heap) or ≥ (max-heap). std::priority_queue gives O(log n) push/pop extremum—used in Dijkstra, top-K, merge K lists.

Array indexing (0-based)

  • Parent of i: (i-1)/2
  • Left child: 2i+1, right: 2i+2
  • Heapify up/down maintains property

priority_queue demo

#include 
#include 
#include 

int main() {
    std::priority_queue maxHeap;
    maxHeap.push(3); maxHeap.push(7); maxHeap.push(1);
    std::cout << "top=" << maxHeap.top() << "\n";
    maxHeap.pop();
    std::cout << "next=" << maxHeap.top() << "\n";
    return 0;
}

Top-K pattern

Keep size-k min-heap of largest candidates—or max-heap for smallest K—O(n log k).

Important interview questions and answers

  1. Q: Min-heap for Dijkstra?
    A: Extract smallest tentative distance—O(log n) per edge relaxation with binary heap.
  2. Q: Heap vs sorted array?
    A: Heap O(log n) insert; sorted array O(n) insert but O(1) min if already sorted.

Self-check

  1. What is complexity of priority_queue push?
  2. How is heap stored in memory?

Tip: priority_queue defaults to max-heap in C++—use greater<> for min-heap.

Interview prep

Heap operations?

push/pop extremum O(log n).

Top-K?

Size-k heap—O(n log k).

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Heap max O(1)?
  • Top-K use?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump