Lesson 2 of 3
Walk, notebook, promise
Every algorithm in this course answers four questions. How does it walk the data, what does it write down, what promise do its notes keep, and what does it cost? We build the frame on the largest number in a list, then use it to make a duplicate check fast.
Trace a loop that keeps a running maximum and say what every name holds after each pass
State the walk, notebook, promise and cost of a short algorithm
Use the promise to explain why a loop gives the right answer
Count the comparisons of a check-every-pair solution and compare them with a one-pass solution that keeps a set
Write a one-pass duplicate check that looks in a set before adding to it
Say the frame out loud before typing, the way the plan phase of a coding round asks
An interviewer opens with a warm-up: return the largest number in a list. You know the answer is max(nums). Then comes the second half: "Without max, please, and talk me through it."
Writing the loop is the small part. Saying why it is right, in plain words, while someone listens, is a separate skill, and it is the one this lesson builds.
The previous lesson used four words to describe count_above: walk, notebook, promise, cost. Together they are the frame: one way of talking that works for every problem in this course. Here we build them slowly on the largest number, then use them on a second problem, where they turn a slow answer into a fast one.
One look at a time
How does a computer find the largest number? It can look at only one number at a time. It cannot glance at [5, 3, 8, 9, 2] and spot the 9 the way you do. So it does what you would do with a stack of cards turned face down: turn over one card at a time, and keep the biggest card so far in your hand. Each new card either beats the one in your hand or it does not.
That gives the first two parts of the frame. The walk is the order in which we visit the data: here, left to right, each number once. The notebook is what we write down as we go: here, one number called best, the largest seen so far.
In Python the walk is a for loop. for x in nums: runs the indented lines under it once per item, with the name x pointing at the current item. Each run of those lines is one pass.
The trace below runs the loop on [5, 3, 8, 9, 2], inside a function called largest: code on the left, every name and its value on the right. Press Next to run one line at a time. The highlighted line is the one about to run, and the change line under the buttons says what the last line to run changed. Before you start, guess: after best starts at 5, how many times will it change?
def largest(nums):best = nums[0]for x in nums:if x > best:best = xreturn best
(nothing printed yet)x and best are two names with two jobs. x is the number we are looking at, and it moves on every pass. best is the notebook, and it moves only when the current number beats it. Read the loop by asking two separate questions on each pass: what is x now, and did best change?
Try it on a new list before we go on.
This is the running-maximum loop from the trace, outside a function, with one extra line: it prints best at the end of every pass. Type exactly what it prints, one value per line.
nums = [4, 1, 7, 3, 8]
best = nums[0]
for x in nums:
if x > best:
best = x
print(best)
The promise
How do we know the loop is right for every list, not only the ones we tried? Trying lists gives evidence, not a reason. The reason is a promise: a sentence about the notebook that is true after every pass. For the largest number:
Check it against the trace. After three passes, the numbers visited are 5, 3 and 8, and best is 8. After four passes, 9 has joined them, and best is 9. Each pass keeps the promise: if the new number is bigger, it becomes best; if not, the old best is still the largest.
Two moments need care. The starting value must not break the promise. best starts at nums[0], a number from the list, so after the first pass it is the largest of the one number visited. Starting at 0 instead breaks it on [-5, -2, -9]. After the first pass the only number visited is -5, but best is 0. No number beats 0, so the loop returns 0, which is not even in the list. (An empty list has no nums[0], so Python stops with an IndexError, its error for a position that does not exist. Ask the interviewer what an empty list should return.)
After the last pass, "the numbers visited so far" means all of them, so the promise says best is the largest number in the list. The promise has turned into the answer. That is the whole proof, and it is the argument an interviewer wants to hear. Interviewers and textbooks call the promise an invariant: a fact that stays true after every step while the values around it change.
The same loop runs on a new list:
nums = [2, 7, 4, 9, 6]
best = nums[0]
for x in nums:
if x > best:
best = x
Which statement is true right after the third pass of the loop body?
Choose one answer, then check.
The cost, and the frame card
One question is left: how much work is it? Count the steps. The comparison x > best runs once per number: 5 times for 5 numbers, 1,000 times for 1,000. The work grows in step with the length of the list. We write that as O(n), read "order n", where n is the number of items. The extra memory is two names, best and x, however long the list is: a fixed amount, written O(1). Module 2 makes this notation exact; for now, those two readings are enough.
That is the fourth question, the cost: time (how many steps) and space (how big the notebook gets). Here are all four answers on one card. Every pattern and every problem in this course ends with a card like this one.
The answers depend on each other, in order. The walk decides what the notebook can know. The notebook decides what promise it can keep. The walk and the notebook together decide the cost. When a new problem has you stuck, find the first of the four you cannot answer yet.
Before you write one from a blank editor, rebuild largest from its shuffled lines. Two of the lines do not belong: one breaks the promise at the start, and one ends the walk too soon.
Put the lines in order to build largest(nums), which returns the largest number in a non-empty list, the loop from the trace. Indentation is already part of each line. Two of the lines do not belong.
Add lines from the list below, in order.
best = xfor x in nums:return bestif x > best:def largest(nums):return bestbest = nums[0]best = 0
The frame works for anything you can compare, not only numbers. Write this one yourself: the notebook holds a word, and the comparison is on length.
Write longest_word(words), which returns the longest word in a non-empty list of words. If several words tie for longest, return the first of them. len(w) is the number of characters in w. Use a loop, not max: the point is the walk. Then press Watch it run to see the notebook change.
raise NotImplementedError, then press Run tests. Each check says what it expects.Checking every pair
Second problem: does any number appear more than once in a list? On [4, 9, 2, 7, 2] the answer is yes (the 2). On [4, 9, 2, 7] it is no.
In an interview, the first approach to say out loud is the plain one, the brute force: the approach that tries every possibility, with no cleverness. Here, that means comparing every pair of numbers. The walk now visits pairs, not single numbers, so it needs two loops, one inside the other (a nested loop). The outer loop picks a position i; the inner loop picks every position j to the right of i.
Three pieces of Python make that work. nums[i] reads the item at position i, counting from 0, and len(nums) is the number of items. range(a, b) produces the whole numbers from a up to, but not including, b, and range(n) is short for range(0, n). On our list of 5 numbers, range(len(nums)) is 0, 1, 2, 3, 4: every position. When i is 1, range(i + 1, len(nums)) is range(2, 5), which is 2, 3, 4: every position to the right of i. Starting j at i + 1 compares each pair once and never compares a number with itself.
The trace below counts comparisons in a name called comparisons, so we can watch the cost grow. The arrows under the list show where i and j point. Before you step through, guess: what will comparisons be when the function returns True?
def has_duplicate(nums):comparisons = 0for i in range(len(nums)):for j in range(i + 1, len(nums)):comparisons += 1if nums[i] == nums[j]:return Truereturn False
(nothing printed yet)Count the pairs yourself, first by hand, then without writing them all out.
On paper, run the pair version on [4, 9, 2, 7], a list with no duplicate. Write every pair of positions (i, j) it compares, in the order the loops visit them, then count them. Reveal one step at a time to check.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
The pair version runs on a list of 6 numbers with no duplicate. How many comparisons does it make before it returns False? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
With no duplicate, the walk checks every pair, and the count follows a pattern. In a list of n numbers, the first number has n − 1 partners to its right, the next has n − 2, and so on down to the last, which has none. For 5 numbers that is 4 + 3 + 2 + 1 + 0 = 10.
A shortcut gives the total for any n. Each of the n numbers could pair with the n − 1 others, which gives n(n − 1), but that counts every pair twice, once as (0, 1) and once as (1, 0). Halve it: n(n − 1)/2 comparisons. That is 5 × 4 / 2 = 10 for 5 numbers, 6 for 4, 15 for 6, and 499,500 for 1,000. The count grows with the square of n (double the list and the work roughly quadruples), and we write that as O(n2).
A set as the notebook
Can one walk do it? Look at where the brute force wastes work. Every time i moves on, the inner loop looks again at numbers it has already seen. A better notebook would remember them for us. So: walk left to right once, and write each number down after looking at it. For each new number, ask one question: is it already in the notebook? If yes, it appeared earlier, and that is a duplicate.
The notebook must answer "is x in here?" fast. A Python list cannot: x in a_list checks the items one by one. A set can. A set is a collection with no repeats and no positions, like the result of SELECT DISTINCT. seen = set() makes an empty one, seen.add(x) puts x in it, and x in seen answers True or False in about the same time however many items the set holds (on average; module 3 shows how). One x in seen question is called a lookup.
Here is the same list, [4, 9, 2, 7, 2], with a set for a notebook. checks counts the lookups. Guess first: what will checks be when the function returns True?
def has_duplicate(nums):seen = set()checks = 0for x in nums:checks += 1if x in seen:return Trueseen.add(x)return False
(nothing printed yet)The order of the two moves matters: check first, then add. If you add x before asking whether it is in the set, the very first number finds itself. On [4, 9], adding 4 and then asking 4 in seen answers True on the first pass, although 4 appears once. Every non-empty list would look like it has a duplicate. Put the lines in order yourself.
Put the lines in order to build has_duplicate(nums) with a set as the notebook. It returns True if any number appears twice and False otherwise. Indentation is already part of each line. Two of the lines do not belong.
Add lines from the list below, in order.
seen = set()seen = set()if x in seen:def has_duplicate(nums):return Truefor x in nums:return Falsereturn Falseseen.add(x)
The promise is what makes it correct. Before each check, seen holds every number to the left of x, and those numbers are all different. If x is in seen, it matches a number to its left: a duplicate. If not, x joins the set, and the numbers visited are still all different. When the walk ends with no match, "the numbers to the left" means all of them, so every number in the list is different from the others, and False is the right answer.
A bigger notebook bought a shorter walk. The pair version keeps no memory but compares every pair. The set version spends memory so that it looks at each number once. Here is the gap for lists with no duplicate, where both versions do their most work:
| Numbers in the list | Pair comparisons, n(n − 1)/2 | Set lookups, n |
|---|---|---|
| 5 | 10 | 5 |
| 1,000 | 499,500 | 1,000 |
| 100,000 | 4,999,950,000 | 100,000 |
At 100,000 numbers, the pair version makes about 50,000 comparisons for every lookup the set version makes. Trading memory for fewer steps is one of the most common moves in this course, and an interviewer expects you to name both sides of the trade.
The interviewer asks: "What does the set version cost?" Which answer is complete and correct?
Choose one answer, then check.
Now write a variation from a nearly blank function. This time, return the repeated number itself, not True.
Write first_repeat(nums), which walks the list left to right and returns the first number whose value has already appeared earlier in the walk. If no number repeats, return None, Python's value for "nothing". Use a set as the notebook.
For [2, 5, 5, 2] the answer is 5: the walk reaches the second 5 (position 2) before the second 2 (position 3).
A return inside the loop stops the walk at once, the way return True does in the set version. So the "no repeat" answer, return None, goes after the loop, where it runs only when the walk ended without finding one. (The lesson Decisions and functions, in module 1, covers this in full.)
raise NotImplementedError, then press Run tests. Each check says what it expects.Recap. The pair version walks every pair with no notebook: O(n2) time, O(1) space. The set version walks once and remembers what it passed: O(n) time, O(n) space. Its promise, that the set holds every number to the left of x and those numbers are all different, is why its answer is right.
Say it before you type
What should you say before you start typing? The frame, out loud. The previous lesson split a 45-minute round into phases: clarify, plan, implement, test and summarize. The research digest's script gives the plan three to four minutes: name a brute force and its cost, then a better approach and its cost, say which one you will write and why, and state the invariant before typing. The invariant is the promise. So the plan phase is the frame said out loud, with the brute force and its cost first.
Here is that plan for the duplicate problem, in words you could say:
"The plain approach compares every pair: about n squared over two comparisons, so O(n2) time and O(1) extra space. Better: I walk the list once and keep a set of the numbers I've passed. The promise is that before I check a number, the set holds every number to its left, and they're all different. If the current number is already in the set, that's a duplicate. A set lookup takes about the same time however big the set is, so the walk is O(n) time, plus O(n) space for the set. An empty list has nothing to repeat, so it returns False. I'll write the set version, because O(n) time is worth O(n) memory unless memory is tight."
Notice what that does. Every one of the four questions gets an answer, and both costs come without anyone asking for them. The digest lists two parts of the bar for an L4-level round that this plan already meets: complexity stated unprompted, and edge cases raised without being asked (here, the empty list).
One practical note before you practice on LeetCode. LeetCode wraps the same function in a class. For this problem (LeetCode 217, Contains Duplicate, which module 3 solves in full), the editor starts you with a method called containsDuplicate. A method is a function that lives inside a class.
from typing import List # LeetCode imports this for you
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False
The body is the set version from the trace, without the counter. class Solution: holds the method. self is an extra first parameter that Python fills in when LeetCode calls your method, so you can ignore it. nums: List[int] and -> bool are type hints: notes saying that nums is a list of integers and that the answer is True or False. Python does not check them. This lab writes problems as plain functions; on LeetCode, put the same body inside the class.
Last, say one yourself. Use the four answers, in order, the way the plan phase asks.
Before typing, explain to an interviewer how you would count how many numbers in a list are even. A number is even when x % 2 == 0 (dividing by 2 leaves no remainder). Cover the walk, the notebook, the promise and the cost, in that order, in a few plain sentences.
Saved in this browser as you type.