Big-O: Reading Cost From Code, With Handshakes and a Guest Book
Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.
What you will learn
- Count the steps a job takes and watch how they grow with the list
- Tell an O(n) single pass from an O(n squared) loop inside a loop
- Explain why cost is planned for the worst case
- Replace a pairwise check with a set lookup in Python
Before you start
- Python loops and lists
- What a data structure is
Why does some code get slow? Big-O answers that with a simple idea. You count the steps your code takes, and you watch how those steps grow when the list grows.
Did anyone sign up twice?
Emma is collecting sign-ups for a school trip. Every student gets an id number, and there are five sign-ups: 12, 7, 9, 4 and 9. Did anyone sign up twice? Yes, 9 is there two times. With five sign-ups, any check answers in a blink.
Now imagine the whole city signs up: one hundred thousand sign-ups. The very same check can make the app freeze. To see why, you'll count the steps two different ways.
Handshakes or a guest book?
Picture four friends at a party, Emma, Jack, Tom and Kate, and everyone wants to shake hands with everyone else. Four friends means six handshakes. Ten friends means 45, and a hundred friends means 4,950.
Now the other way. Put a guest book at the door. Each guest is looked up once and then written in. If a name is already in the book, that person came twice. A hundred guests means only a hundred look-ups.
Handshakes grow like the list times the list. The guest book grows just like the list.
The main script
sign_up_app.py runs both checks on the same five ids:
from handshake_check import HandshakeCheck
from guest_book_check import GuestBookCheck
# five sign-up ids, and 9 is in there twice
ids = [12, 7, 9, 4, 9]
twice = HandshakeCheck.has_duplicate(ids)
print(f"Handshake: {twice}, steps = {HandshakeCheck.steps}")
# now the same check with the guest book
twice = GuestBookCheck.has_duplicate(ids)
print(f"Guest book: {twice}, steps = {GuestBookCheck.steps}")
Handshake: True, steps = 9
Guest book: True, steps = 5
Same answer, a different number of steps. That number is exactly what makes code slow.
Inside HandshakeCheck
class HandshakeCheck:
# compare every sign-up with every other one
steps = 0
@staticmethod
def has_duplicate(ids):
for i in range(len(ids)):
for j in range(i + 1, len(ids)):
HandshakeCheck.steps += 1
if ids[i] == ids[j]:
return True
return False
steps goes up by one every time two ids are compared. The outer loop picks one sign-up with i. The inner loop walks over every sign-up after it, which is why j starts at i + 1. If ids[i] == ids[j], the same id is there twice, so it stops and returns True.
Play it on 12, 7, 9, 4, 9. First 12 meets 7, 9, 4 and 9: four steps, all different. Then 7 meets 9, 4 and 9: steps five to seven. Then 9 meets 4 (step eight) and 9 (step nine). Nine equals nine, so it returns True after nine steps.
Inside GuestBookCheck
class GuestBookCheck:
steps = 0
# write each id in the book, stop if it is already there
@staticmethod
def has_duplicate(ids):
book = set()
for sign_up in ids:
GuestBookCheck.steps += 1
if sign_up in book:
return True
book.add(sign_up)
return False
The guest book is a set, which remembers every value you put in it. There's just one loop, so each id is looked at once. If the id is already in the book, it returns True. Play it: 12, 7, 9 and 4 are new and get written in. Step five is 9, and 9 is already in the book. Five steps.
Why is sign_up in book one step and not a search? A set is a hash table. The book is split into labelled pages, and the number itself tells you which page to open, so you never read the whole book. Hash tables shows how that works.
The worst case: no repeat
Now suppose nobody signed up twice: four different sign-ups, 12, 7, 9 and 4. The handshake way compares 12 with 7, 9 and 4, then 7 with 9 and 4, then 9 with 4. That's six steps, every pair, and none matched. Only then can it say no.
That's the worst case, because nothing let you stop early. A repeat near the front would have saved you, but you can never count on that luck. So when you talk about cost, you always plan for the worst case.
Grow the list
Nine versus five is no big deal. So grow_app.py tries three sizes, and gives every sign-up a different id so both checks have to go to the very end:
from handshake_check import HandshakeCheck
from guest_book_check import GuestBookCheck
# try three sizes
for n in (100, 1_000, 10_000):
# every sign-up gets a different id, no repeats
ids = list(range(n))
HandshakeCheck.steps = 0
GuestBookCheck.steps = 0
HandshakeCheck.has_duplicate(ids)
GuestBookCheck.has_duplicate(ids)
print(f"{n:7,d} ids: handshake {HandshakeCheck.steps:13,d}"
f" book {GuestBookCheck.steps:7,d}")
100 ids: handshake 4,950 book 100
1,000 ids: handshake 499,500 book 1,000
10,000 ids: handshake 49,995,000 book 10,000
Ten times the ids means ten times the steps for the guest book, but about a hundred times the steps for the handshakes. At 10,000 ids it's 10,000 steps against almost 50 million.
Read the cost off the code
Here's the nice part: you can read the cost straight off the code. One loop over n items is about n steps. A loop inside a loop is about n times n steps. That way of writing the cost is Big-O.
| Check | Shape of the code | Big-O | Steps at 10,000 ids |
|---|---|---|---|
| Guest book | one loop, set lookup | O(n) | 10,000 |
| Handshakes | loop inside a loop | O(n2) | 49,995,000 |
The handshake way does about five thousand times more work at that size. In a big app with lots of users, that's the difference between fast and frozen.
Where you meet this
A site checking your username at sign-up doesn't compare it with every account; it looks it up, like the guest book. A game checking every object against every other object is the handshake way, so big games group objects into zones first. A database matching two tables builds a lookup instead of matching every row with every row. And simple sorting methods that compare every pair slow down fast, while good ones need far fewer steps.
Recap
- Count the steps, not the lines, and watch how they grow with the list.
- One pass over the list is O(n). A loop inside a loop is O(n2), and it gets slow fast.
- Plan for the worst case, and use a lookup when you can.
Try it yourself: in sign_up_app.py, give every sign-up a different id, and predict both step counts before you run it. Then see what Big-O means for a real structure in arrays and dynamic arrays.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
Recursion: Russian Dolls, the Base Case and the Call Stack
Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.
Linear vs Binary Search: Page by Page, or Open in the Middle
Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.
Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.
Merge Sort: Split the Pile, Then Merge Two Sorted Piles
Ms Kate's eight exam papers sorted in 24 steps: split in half until each pile is one paper, then merge sorted piles by taking the lower top. A million papers take about 20 million steps, and the price is extra room.
