DSA
    intermediate

    Heap (Priority Queue)

    Software Engineer path · lesson 17 of 99
    O(log n)

    Syntax: push n · pop. Numbers from -99 to 99.

    Try:
    Heap type

    Empty heap

    array0
    ComparingMovedSettled

    Empty max-heap. Stored as an array: children of i are at 2i+1 and 2i+2.

    Code (running line highlighted)
    1. 1push(x): a.append(x); i = last
    2. 2 while i > 0 and a[i] beats a[parent(i)]: swap them; i = parent(i) # sift up
    3. 3pop(): top = a[0]; a[0] = a.pop()
    4. 4 while a child beats a[i]: swap with the better child # sift down
    5. 5 return top # "beats" = smaller in a min-heap, larger in a max-heap
    Comparisons
    0 / 12
    Swaps
    0 / 6
    Invariant: Every parent is ≥ its children, so the maximum is always at index 0.

    Tap any element in the diagram to inspect its state at this step.

    1 / 19

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    What does it cost?

    Sort

    Sort each binary-heap operation by its time complexity.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    O(1)

    Drop items here

    O(log n)

    Drop items here

    O(n)

    Drop items here
    6 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    Where is the maximum element always located in a Max Heap?

    The short version

    Think of an emergency room triage. Patients are not treated in order of arrival (FIFO), but by severity. The most critical case (highest priority) is always handled next, regardless of wait time.

    In more depth

    The Priority Struct

    A Heap is a specialized Tree-based data structure that satisfies the Heap Property. It is the most efficient way to repeatedly access the Highest or Lowest priority element.

    Array Representation:

    Heaps are typically implemented as arrays!

    Left Child: 2*i + 1
    Right Child: 2*i + 2
    Parent: floor((i-1)/2)

    When to reach for this

    • Find the **Top K** elements
    • Find the **Median** of a stream
    • Schedule tasks by Priority

    Interview Questions

    Facebook
    Amazon
    LinkedIn
    Google
    Uber
    Apple
    Microsoft
    Bloomberg
    Facebook
    Amazon
    Airbnb
    Microsoft

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required