Big-O & Complexity
In short: a data structure is just an organised way to hold data — an array, a hash table, a tree — chosen so the operations you actually need stay cheap as the data grows. Big-O is how you compare them: not a stopwatch reading, but how many basic steps an operation takes for an input of size n, and how that count grows as n grows. Pick the wrong structure and a feature that felt instant at 40 songs crawls at 40 million. This whole course is "know the shape of the cost before your users find it."

Search Tunebox's library
A scan checks every song until it finds a match:
Same code, wildly different cost depending only on where the song sits:
The same scan costs 1 step or n steps depending only on where the song sits, which is why a bare Big-O quotes the worst case.
Looking for Glow: it sits in slot 0, so the scan stops after 1 comparison. That's the best case. 5 cells. At index 0. 1 of 5 cells settled.
That's best case (1 step), worst case (n steps) and average case (about n/2 steps) — one function, three numbers. A bare "scanning is O(n)" means the worst case — the promise you make to every user. The mistake: test with the lucky song at position 0 and promise that speed to everyone.
Binary search beats a scan by halving the field each step instead of walking it one at a time — but only works on a sorted list:
Doubling n adds only one more halving: 1,000 songs takes 10 steps, a
million takes 20. A dict lookup by id skips the search entirely — O(1), one
hash, done. Three structures, three costs for "find one song":
| Big-O | name | Tunebox example |
|---|---|---|
| O(1) | constant | look up a song by id in a dict |
| O(log n) | logarithmic | binary search a sorted list of titles |
| O(n) | linear | scan every song for a title |
| O(n log n) | linearithmic | sort the library by play count |
| O(n²) | quadratic | compare every pair of songs for duplicates |
| O(2ⁿ) | exponential | try every subset of songs to fill exactly 60 minutes |
Big-O also drops constants and small terms — 2n and 500n are both O(n),
and 3n² + 5n + 100 is O(n²), because at n = 1,000 the n² term is
3,000,000 and the rest is a rounding error. Loops one after another add
(two n-loops back to back is still O(n)); loops nested inside each other
multiply (O(n²)):
def work(n):
steps = 0
for i in range(n):
steps += 1
for i in range(n):
steps += 1
return steps
print(work(10), work(20))