Algorithms · The shape of every puzzle
Find the maximum
Find the biggest number in a list, without max().
The problem
Return the biggest number in nums (it has at least one number). The code in the editor already works. It checks every number against every other number. Make it look at each number only once.
biggest([3, 41, 7, 19, 2])→41biggest([5])→5Start with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def biggest(nums):take a list of numbers for a in nums:try each number as the answer beaten = Falseassume nobody beats it for b in nums:compare it with every number if b > a:is someone bigger? beaten = Truethen it isn't the biggest if not beaten:nobody was bigger return aso this is the biggestNow ask: what if there were a billion?
With a billion numbers spread over 1,000 computers, each computer finds its own biggest, then you compare just the 1,000 winners. That split-then-combine trick is how Google’s MapReduce works.
Aim for O(n)🌱 warm-up
Think it through
The obvious way compares every number with every other. For 1,000 numbers, about how many comparisons is that?
- About 1,000
- About a million
Show the answer
About a million. Every number against every number is n × n. At a million numbers that’s a trillion steps: hours. Spotting “every pair” is the first step to making code fast.
Reading the list once, left to right, what do you need to remember?
- Every number so far
- Just the biggest so far
Show the answer
Just the biggest so far. A “champion so far”: each new number only has to beat the champion. One pass, one variable. This keep only what you need move comes back in half the puzzles.
Stuck? 3 nudges, smallest first
- Imagine reading the list out loud. You only need to remember one number as you go.
- Keep a “champion so far”. Start with the first number.
best = nums[0], then for eachx, ifx > best, setbest = x. Returnbest.
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def biggest(nums):take a list of numbers best = nums[0]the champion so far: the first number for x in nums:look at each number once if x > best:does it beat the champion? best = xit's the new champion return bestthe last champion standingWhere it’s used for real
Solve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.