Understanding How Things Scale in Everyday Life
Tip
Let’s explore Complexity Levels that describe how things scale in real life!!
Topics covered in today’s discussion:
Note
Important
Now that you can write programs, we need to understand how to make them efficient. Efficiency is all about how fast your program runs and how much memory it uses, especially as the input size grows.
Efficiency is important because:
Note
Complexity = How much more work do you need when you have more stuff to deal with?
Real-Life Examples:
(One that every programmer will wonder!)
When you double the amount of “stuff,” what happens to the amount of work?
That’s what complexity tells us! 🎯
Let’s explore each complexity level! 🚀
“No Matter How Much, It Takes the Same Time!” 🎪
O(1) means: Whether you have 1 thing or 1 million things, the task takes exactly the same amount of time!
Everyday O(1) Examples:
🔑 Using a key to open your door - Same one turn always!
💡 Turning on a light switch - Same flip always!
📱 Checking the time on your phone - Always instant!
🏧 Using your debit card - Same swipe time always!
The Holy Grail of Algorithms! 🏆
✨ It’s like magic - the amount of work never changes
🎯 Perfect performance - always fast, always reliable
🚀 Every programmer dreams of O(1) solutions!
Real-World O(1) Examples:
“Cut the Problem in Half, Over and Over!” 🔍
O(log n) means: Each step eliminates half of what’s left to search. Super efficient even with huge amounts!
Everyday O(log n) Examples:
🎯 Guessing a number 1-1000 - Cut problem in half each time, found in ~10 questions max!
📖 Finding word in dictionary - Open to middle, go left or right, found in seconds!
🎪 20 Questions game - Each question eliminates half the possibilities
🔍 Phone contact search - Type “J” → cuts to J names, type “Jo” → even fewer options
🗂️ Looking for a file in a sorted filing cabinet - Open to middle, go left or right, found in seconds!
Incredible Scaling Performance! 📊
Amazing scaling: * 1,000 items → ~10 steps * 1,000,000 items → ~20 steps
* 1,000,000,000 items → ~30 steps
🧠 Smart strategy beats brute force
Used everywhere:
The catch: You need things organized first! 📋
(This might take some time, but once it’s done, searching is lightning fast!)
“Check Every Single Thing, One by One” 👀
O(n) means: Double the stuff = Double the work. Fair and predictable!
Everyday O(n) Examples:
📚 Reading every page in a book - 100 pages = 100 page flips, 200 pages = 200 page flips
🛒 Counting items in shopping cart - Must touch each item once, 10 items = 10 counts
🎵 Listening to playlist - 50 songs = 50× the time
📝 Grading test stack - 30 tests = 30× the work
The good news: O(n) is often the best you can do for many tasks
n tasks. You can determine smallest run-time with accuracy!Predictable and Fair! 📈
✅ Predictable and fair - work scales linearly
🎯 Working at scale - Doubling the input only doubles the work, not more!
📈 Reasonable for most tasks: O(n) is often the “best possible” complexity, not just a “good” one. Even though it’s not constant time, it’s: Predictable, Scalable, and Optimal for many real-world problems
When it gets slow:
Really large amounts of data - but still very manageable for normal use! 🎯
“Everyone Must Meet Everyone Else!” 😰
O(n²) means: When you double the people, you get four times the work! This gets crazy fast.
Everyday O(n²) Examples:
🤝 Party introductions - 4 people = 6 handshakes, 8 people = 28 handshakes, 16 people = 120 handshakes!
🏆 Sports tournament - Everyone plays everyone, gets expensive fast!
👥 Group photo arrangements - Every person next to every other, gets overwhelming quickly!
📝 Comparing all student tests - Looking for identical answers, 30 students = 435 comparisons!
Explosive Growth! 💥
📈 Explosive growth:
⚠️ The danger zone - where apps become unusably slow
🐌 Common culprits: * Comparing every item to every other * Nested loops in programming * Poor algorithm choices
When to worry: Anything over ~1,000 items gets really slow! 🚨
“Every Choice Doubles Your Problems!” 🤯
O(2ⁿ) means: Add just one more thing, and you double all the work! This explodes instantly.
Everyday O(2ⁿ) Examples:
🧬 Family tree exploration - 2 parents → 4 grandparents → 8 great-grandparents → 16 great-great-grandparents
🔐 Password cracking - Each digit doubles possibilities, 10-digit PIN = 1+ billion combos!
🎁 Gift wrapping combinations - Each gift: wrapped or not, 20 gifts = 1+ million combinations!
Grows Impossibly Fast! 🚨
💀 Grows impossibly fast:
🚫 Usually unusable for anything but tiny problems
⏰ Real-world impact:
Bottom line: Avoid at all costs unless you have < 20 items! ⚠️
Let’s see what happens when we have 1,000 things to process.
| Complexity | Name | Steps Needed | Real-World Feeling |
|---|---|---|---|
| O(1) | Magic Trick | 1 step | ⚡ Instant! |
| O(log n) | Smart Detective | ~10 steps | 🏃 Super fast! |
| O(n) | One-by-One | 1,000 steps | 🚶 Takes a moment |
| O(n²) | Handshake Problem | 1,000,000 steps | 🐌 Ugh, so slow… |
| O(2ⁿ) | Explosion | 2¹⁰⁰⁰ steps | 💀 Heat death of universe |
Small differences in complexity = HUGE differences in real-world performance!
This is why choosing the right approach matters so much in programming! 🚀
Ready for your challenge? Let’s become complexity detectives! 🕵️♂️
Predict the winner! All three methods get copies of the same list of distinct numbers.
| Algorithm | Status | Comparisons | Time |
|---|---|---|---|
| Merge sort | Ready | — | — |
| Bubble sort | Ready | — | — |
| Bogosort (shuffle!) | Ready | — | — |
Bogosort stops after 25,000 shuffles or about 2 seconds, whichever comes first. “Limit reached” means it did not finish in this run—not that it can never finish.
The browser runs JavaScript implementations in separate workers; times exclude worker startup and result checking. Timing varies with the device and concurrent work. Bogosort’s comparisons count sortedness checks, not shuffle operations.
Try it: Double or change the list size; then compare reverse and already-sorted input. What changes?
Tip
Discuss: Why is already-sorted input especially good for this bubble sort? Why is the number of shuffles not a reliable prediction for just one bogosort run?
Each step compares neighbors or shows the result. Follow the largest value as it moves right.
Yellow: current neighbors · Green: confirmed final positions
Think: After one pass, where is the largest value? When can we stop early?
Follow the recursive splits, then watch sorted halves merge. The display shows the current sublist, not the whole recursion tree.
Current sublist:
Left remaining
Right remaining
Merged output
Think: Why can we append the rest of one half when the other half is empty?
def bubble_sort(items):
values = items.copy() # Keep the original list unchanged.
for end in range(len(values) - 1, 0, -1):
swapped = False
for i in range(end):
if values[i] > values[i + 1]:
values[i], values[i + 1] = values[i + 1], values[i]
swapped = True
if not swapped:
break
return values
print(bubble_sort([5, 1, 4, 2, 3]))How many neighboring comparisons might the nested loops make as the list grows?
def merge_sort(items):
if len(items) < 2:
return items.copy()
middle = len(items) // 2
left = merge_sort(items[:middle])
right = merge_sort(items[middle:])
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
return result + left[i:] + right[j:]
print(merge_sort([5, 1, 4, 2, 3]))In everyday Python, also try sorted(items): it uses Python’s built-in sorting algorithm, not this merge sort.
Actually, why is merge sort faster than bubble sort for large lists? How does the number of comparisons grow as the list size doubles? How does this compare to bogosort?
Both searches inspect the same sorted list 0, 1, …, n - 1. Predict which examines fewer items.
Target value: —
| Method | Result | Items inspected |
|---|---|---|
| Linear search | Ready | — |
| Binary search | Ready | — |
Counts are inspected items, not elapsed time or individual comparison operators. Creating or sorting the list is not included; binary search requires sorted input.
Try it: Compare first, last, and missing targets. When is a linear search a good choice?
The same sorted list is used for both search visualizations, though linear search does not require sorting.
Yellow: item just inspected · Crossed out: no longer a candidate
Try it: Find the first item, then a missing item. How many items did you inspect?
Binary search needs a sorted list. Each inspection can eliminate half of the remaining candidates.
Yellow: item just inspected · Crossed out: no longer a candidate
Try it: Find 15, then 10. Compare the number of inspections with linear search.
Linear search — works on an unsorted list; O(n) worst case.
Discuss: If the list is unsorted and you search only once, should you sort it first? What if you search it many times?
| Task | Complexity | Justification |
|---|---|---|
| 🧑🍳 Cooking a meal for 4 people | ? | ? |
| 📚 Finding a word in a dictionary | ? | ? |
| 🧬 Exploring family tree generations | ? | ? |
| 🧑🤝🧑 Introducing everyone at a party | ? | ? |
| 🔍 Searching for a name in your phone contacts | ? | ? |
| 🎁 Figuring out gift wrapping combinations for 10 gifts | ? | ? |
| 📖 Reading every page in a book | ? | ? |
Important
The below tasks are all over the place! Define the tasks according to complexity: easiest (O(1)) to hardest (O(2ⁿ)). Work in groups to justify your choices! Be prepared to share with the class! 🚀
Now You’re Ready for the Challenges! 🎯
You’ve learned the 5 complexity levels. Time to become complexity detectives and find examples from your own life! Work in groups to come up with a real world task (that you complete!) for each complexity level. Be prepared to share your findings with the class! 🚀
Remember the Levels! 📋
The 5 Complexity Levels:
| Task | Complexity | Estimated Steps Needed |
|---|---|---|
| 🧑🍳 Cooking a meal for 4 people | O(n) | n = number of people (or portions) |
| 📚 Finding a word in a dictionary | O(log n) | n = number of words |
| 🧬 Exploring family tree generations | O(2ⁿ) | n = number of generations |
| 🧑🤝🧑 Introducing everyone at a party | O(n²) | n = number of people |
| 🔍 Searching for a name in your phone contacts | O(n) | n = number of contacts |
| 🎁 Figuring out gift wrapping combinations for 10 gifts | O(n!) | n = number of gifts |
| 📖 Reading every page in a book | O(n) | n = number of pages |
Important
Listed according by easiest (O(1)) to hardest (O(2ⁿ))
🧑🍳 Cooking a meal for 4 people → O(n)
n = number of people (or portions) You typically scale ingredients and prep roughly linearly with servings.
📚 Finding a word in a dictionary → O(log n) (if using a sorted dictionary)
n = number of words Like binary search: you repeatedly halve the search space. If unsorted, it would degrade to O(n).
🧬 Exploring family tree generations → O(2ⁿ) (exponential)
n = number of generations Each generation roughly doubles (2 parents, 4 grandparents, etc.).
🧑🤝🧑 Introducing everyone at a party → O(n²) n = number of people If everyone is introduced to everyone else, you get pairwise interactions.
🔍 Searching for a name in your phone contacts → O(n) (typical case)
n = number of contacts Linear scan if unsorted. Could be O(log n) if perfectly sorted and searched efficiently.
🎁 Figuring out gift wrapping combinations for 10 gifts → O(n!) (factorial)
n = number of gifts If considering all possible orderings or combinations of wrapping, this grows extremely fast.
📖 Reading every page in a book → O(n)
n = number of pages You process each page once.
CS 101 - Algorithm Complexities