Back to DSA Python report

N log N Deep Dive

Interactive complexity notes that connect logarithms, tree height, heap operations, and growth-rate comparisons.

Part 1 — what does log n actually mean?

log₂(n) answers one question: how many times can you halve n before reaching 1?

16
n
16
log₂(n)
4
halvings to reach 1
4

This is exactly the height of a binary tree with n nodes. A tree of 1 million nodes is only 20 levels tall.

Part 2 — the tree height IS log n

Each level of the tree doubles the number of nodes. So the height grows as the inverse of doubling — which is log₂.

LevelNodes at levelTotal nodes so farHeight = log₂(total)
0 (root)110
123≈ 1.6
247≈ 2.8
3815≈ 3.9
k2ᵏ2ᵏ⁺¹ − 1k

Part 3 — why insert is O(log n)

When you insert into a heap, the new element bubbles up from the bottom to its correct position. The maximum distance it can travel = the height of the tree = log₂(n).

16
tree height
4
max swaps (insert)
4

Bubble-up path for n = 15

Inserting a very small value (like 0) — worst case, it travels all the way to the root. Each arrow = one swap = one comparison.

Level 0
5
← 3 swaps up
↑
Level 1
8
12
← 2 swaps up
↑
Level 2
9
15
14
20
← 1 swap up
↑
Level 3
0*
22
25
30
18
16
11
13
← inserted here

0* was inserted at the leaf. It swapped upward 3 times = log₂(15) ≈ 3.9 → rounded to 4. That's O(log n).

Part 4 — why n inserts = O(n log n)

If one insert costs O(log n), and you do n inserts (building a heap by pushing one element at a time), the total cost is:

n × log n
8
total inserts
8
cost per insert (avg)
3
total ops ≈
24

Part 5 — graphical comparison

See how slowly log n grows vs n and n². Drag the slider to feel the difference.

32

At n = 1024: n² = 1,048,576 operations. n log n = 10,240. log n = just 10. That gap is why we care about complexity.

Part 6 — the full picture

OperationWhy log n?Total for n elements
Insert (push)bubble up ≤ tree heightO(n log n)
Delete min (pop)sift down ≤ tree heightO(n log n)
heapifymost nodes near leaves (short trips)O(n) — better!
Heap sortn pops, each O(log n)O(n log n)

heapify is O(n) not O(n log n) because it builds bottom-up — lower nodes (majority) sift down only 1–2 levels, not log n levels. The math sums to O(n).