Big O Notation

Big O notation, visually, with nothing to memorize. Two searches race through the same 32 sorted numbers: one checks them one by one, the other cuts the list in half on every step. Then you’ll see what log N actually means, how six common growth rates pull apart, and a Big O cheat sheet to keep.

The video below explains the idea visually.

The one question Big O answers

Big O answers one question: when the amount of data grows, how fast does the work grow?

That’s it. It does not tell you how many seconds a program takes. Seconds depend on your computer, your language, the weather. Big O ignores all of that and looks only at the shape of the growth.

The letter N always means “how much stuff there is”: the number of items in a list, names in a phone book, users in a database. When you see O(N), O(log N) or O(N²), read it as “the work grows like N”, “grows like log N”, “grows like N times N”.

You don’t need to memorize anything in this guide. Each idea comes from asking: if I double my data, what happens to my work?

The core idea: count steps, then double the data

Imagine a stack of 100 exam papers and three different jobs.

  1. Grab the top paper. It takes 1 step. With 200 papers it is still 1 step. The work does not care how big the stack is.
  2. Find the paper with the name “Zoe” in an unsorted stack. In the worst case you check every paper: 100 steps. With 200 papers, 200 steps. Double the data, double the work.
  3. Check if any two papers have the same score. Compare every paper with every other paper: about 100 × 100 = 10,000 comparisons. With 200 papers, 40,000. Double the data, four times the work.

Those three behaviours are O(1), O(N) and O(N²). The names are just labels for “what happens when I double the data”:

Double the data and the work…Big O
stays the sameO(1)
grows by just one extra stepO(log N)
doublesO(N)
a bit more than doublesO(N log N)
quadruplesO(N²)
squares itself (explodes)O(2ⁿ)

Why Big O throws away details

If a program does 3N + 5 steps, Big O calls it O(N). If it does N² + 100N, it is O(N²). Why drop the extra parts?

Because when N gets big, only the fastest-growing part matters. At N = 1,000,000, N² is a trillion while 100N is a mere hundred million: less than 0.01% of the total. The “3” in 3N just means a slightly slower computer; it doesn’t change the shape. Big O keeps the shape and drops the noise.

“Worst case” by default

When people say “linear search is O(N)” they usually mean the worst case: “Zoe” is the last paper, or not there at all. Sometimes you get lucky, but Big O promises you will never do worse than this.

Logarithms without fear: it’s just halving

Forget the math-class definition. In programming, a logarithm answers one simple question:

How many times can you cut N in half before you get down to 1?

That number is log N (people mean log base 2, which fits halving).

Try it with 16:

  1. 16 → 8 (one cut)
  2. 8 → 4 (two cuts)
  3. 4 → 2 (three cuts)
  4. 2 → 1 (four cuts)

Halving 16 down to 1 takes 4 cuts, so log 16 = 4 (■ = still to search, □ = thrown away):

Start: 16 left   ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
Cut 1:  8 left   ■ ■ ■ ■ ■ ■ ■ ■ □ □ □ □ □ □ □ □
Cut 2:  4 left   ■ ■ ■ ■ □ □ □ □ □ □ □ □ □ □ □ □
Cut 3:  2 left   ■ ■ □ □ □ □ □ □ □ □ □ □ □ □ □ □
Cut 4:  1 left   ■ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □

Four cuts, so log 16 = 4. That’s all a logarithm is.

Turn it around: doubling

The same idea works backwards. log N is also “how many times do I double 1 to reach N?” 1 → 2 → 4 → 8 → 16 is four doublings. So doubling and logarithms are two sides of one coin: doubling grows fast, so its opposite, the logarithm, grows slowly.

The surprising part

Because doubling gets huge quickly, halving brings huge numbers down quickly:

N (how much data)log N (halvings to reach 1)
83
1,000about 10
1,000,000about 20
1,000,000,000about 30
8,000,000,000 (every person on Earth)about 33

A thousand times more data adds only about 10 to log N. Keep that table in mind; it’s the whole reason the next section exists.

A quick trick to estimate log N

2¹⁰ = 1,024, which is roughly 1,000. So every time you multiply N by 1,000, log N goes up by about 10. Thousand → 10, million → 20, billion → 30. No calculator needed.

Why log N matters

O(log N) means you can handle enormous data with almost no extra work: a billion items takes about 30 steps.

The phone book story

You need to find “Martinez” in a phone book of 1,000 names.

  • One by one (O(N)): start at page 1 and read every name. Worst case: 1,000 checks.
  • Halving (O(log N)): open the book in the middle. You land on “Lee”. Martinez comes after Lee, so the whole first half is useless; throw it away. Open the remaining half in the middle, and repeat. Every check cuts the problem in half, so after about 10 checks you’re done.

That halving trick is called binary search, and it’s the classic O(log N) algorithm.

Finding one name: worst-case checks, one by one vs halving

Names in the list (N)One by one: O(N)Halving: O(log N)
1001007
5005009
1,0001,00010
1,000,0001,000,00020
1,000,000,0001,000,000,00030

The one-by-one count keeps climbing; the halving count barely moves.

The rule of thumb

When each step throws away half of what’s left, the algorithm is O(log N). You don’t need to calculate anything: spot the halving and you’ve spotted the log.

You already know this game. “I’m thinking of a number from 1 to 100” can always be won in 7 guesses if you guess the middle each time, because 100 halves down to 1 in about 7 cuts.

Where log N shows up in real life

  • Databases. An index lets a database find one row among millions in about 20 steps instead of reading every row. That’s the difference between a page loading instantly and timing out.
  • Balanced trees (and the sorted maps and sets built on them). Each step down the tree discards half the remaining items.
  • Debugging with git bisect. Searching 1,000 commits for the one that broke the build takes about 10 tests, not 1,000.
  • Fast sorting. Merge sort splits the list in half again and again (log N levels) and does N work on each level, which gives O(N log N).

The catch

Halving only works when the data is sorted or organised (like a tree). You can’t binary-search a messy pile. Sorting costs O(N log N) once, but after that every lookup is O(log N), which pays off quickly when you search many times.

The common Big O classes

Almost every algorithm you meet falls into one of six classes. They are listed fastest to slowest; the last two columns show how the work changes when N goes from 1,000 to 1,000,000.

Big ONicknameEveryday pictureCode exampleSteps at N=1,000Steps at N=1,000,000
O(1)ConstantGrab the top paper off the stackRead array[5], hash map lookup11
O(log N)LogarithmicFind a name in a phone book by halvingBinary search, balanced tree lookup~10~20
O(N)LinearRead every name in the book onceLoop over a list, find the max1,0001,000,000
O(N log N)“N log N”Sort by splitting in half, then mergingMerge sort, built-in sort()~10,000~20,000,000
O(N²)QuadraticEveryone shakes hands with everyone elseTwo nested loops, bubble sort1,000,0001,000,000,000,000
O(2ⁿ)ExponentialTry every combination of N switchesBrute-force all subsetsmore than atoms in the universedon’t even try

How to read each one

  • O(1): the size of the data doesn’t matter at all. The dream.
  • O(log N): the data can grow a thousand times and you add only ~10 steps. Nearly as good as O(1) in practice.
  • O(N): fair and honest: you touch each item once. Usually fine.
  • O(N log N): a little worse than O(N). This is the best possible speed for sorting by comparing items, so it’s considered excellent.
  • O(N²): fine for 100 items, painful for 100,000. A common sign: a loop inside a loop.
  • O(2ⁿ): every extra item doubles the work. Usable only for tiny N (around 30 or less).

How to work out Big O yourself

Look at what the code does to the data, and ask these questions in order. The first “yes” is your answer:

  1. Same work no matter how big N is? → O(1)
  2. Does each step throw away half of what is left? → O(log N)
  3. Does it try every combination (each item either in or out)? → O(2ⁿ)
  4. Is there a loop over N inside another loop over N? → O(N²)
  5. Is N work repeated log N times (split in halves, then merge)? → O(N log N)
  6. Otherwise: one simple pass over the data → O(N)

Four short examples

# O(1): one step, whatever the size of the list
def first(items):
    return items[0]

# O(N): might look at every item once
def contains(items, target):
    for item in items:
        if item == target:
            return True
    return False

# O(N²): a loop inside a loop, every pair compared
def has_duplicate(items):
    for i in range(len(items)):
        for j in range(i + 1, len(items)):
            if items[i] == items[j]:
                return True
    return False

# O(log N): every pass throws away half of what is left
def binary_search(sorted_items, target):
    low, high = 0, len(sorted_items) - 1
    while low <= high:
        mid = (low + high) // 2
        if sorted_items[mid] == target:
            return mid
        if sorted_items[mid] < target:
            low = mid + 1    # drop the left half
        else:
            high = mid - 1   # drop the right half
    return -1

Three rules for combining pieces

  • One after another → keep the biggest. A loop (N) followed by a nested loop (N²) is O(N²). The small part stops mattering as N grows.
  • One inside another → multiply. A loop of N steps that does a binary search (log N) each time is N × log N = O(N log N).
  • Fixed numbers disappear. Two separate loops over the list is 2N steps, still O(N). Doubling the data still doubles the work, and that shape is all Big O records.

The whole idea in five sentences

  1. Big O describes how the work grows when the data grows, not how many seconds it takes.
  2. Find it by asking: "if I double N, what happens to the work?"
  3. log N is just "how many times can I cut N in half?", and it stays tiny even for huge N (a billion → about 30).
  4. Whenever an algorithm throws away half the data at each step, it's O(log N), and that's why sorted data, trees and database indexes are so fast.
  5. Keep only the fastest-growing part and ignore fixed numbers: that's all the "O" is doing.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.