Lesson 3 of 5
Counting and seen-before
Two notebooks that the rest of this module builds on. A dict from item to count answers "how many of each?", and a set or dict of what you have passed answers "have I met this before?". Two sum puts the second one to work.
Count how many times each item appears with a dict, in one walk
Decide whether two strings are anagrams by comparing their letter counts
Spot a repeat with a set of the items already passed, checking before adding
Solve two sum in one walk by looking up each number's partner in a dict of positions
Say why the two sum notebook stores positions and why the lookup comes before the store
A table of log events has a column called level: warn, error, warn, info, warn. Two questions about it come up all the time. How many events of each level are there? And, as each event arrives, have I met this value before? In SQL the first is a GROUP BY with COUNT(*), and the second is what a deduplication step answers.
In Python, each question is one walk over the data with a hash map as the notebook. A hash map is the structure behind Python's dict and set: it finds a key in about one step on average, however many keys it holds. The previous lesson looked inside one. This lesson puts it to work.
The first notebook is a dict from item to count. The second is a set of the items already passed, checked before each new item goes in. We trace each one, solve two problems with them, and then use the second on two sum, problem number 1 on LeetCode. The rest of this module builds on both.
Counting: a dict from item to count
How many times does each value appear? A dict maps keys to values: here each key is an item, and its value is how many times we have met that item so far. Checking for a key (level in counts) and reading or changing its value (counts[level]) each take about one step on average.
The walk visits each item once and asks it one question: is this item in the dict yet? If it is, add one to its count. If not, this is its first appearance, so its count starts at 1.
Before you step through, guess the dict this function returns for ["warn", "error", "warn", "info", "warn"].
def count_levels(levels):counts = {}for level in levels:if level in counts:counts[level] += 1else:counts[level] = 1return counts
(nothing printed yet)Notice the order of the rows: warn, error, info, the order in which each level first appeared. A dict keeps its keys in the order they were first added (Python guarantees this since version 3.7), and it prints them in that order.
The loop is right because of its promise:
Check it against the trace: after three passes the items visited are warn, error and warn, and counts is {"warn": 2, "error": 1}. When the walk ends, "visited so far" means every item, so the promise is the answer.
The one-line update
The if and else fold into one line with .get, the tool from the previous lesson's counting trace. A reminder: counts.get(level, 0) returns counts[level] when the key is there and 0 when it is not. Add one and store the result:
counts[level] = counts.get(level, 0) + 1
You will write this line again and again in this module. The previous lesson also warned against the shorter counts[level] += 1. Check that you remember why.
This version skips the if and adds one straight away:
counts = {}
for level in ["warn", "error", "warn"]:
counts[level] += 1
print(counts)
What happens when it runs?
Choose one answer, then check.
Now read the .get version on a string. A for loop over a string visits its characters one at a time.
Type exactly what this prints. Python prints a dict as {key: value, ...}, with strings in single quotes and the keys in the order they were first added.
counts = {}
for ch in "tattoo":
counts[ch] = counts.get(ch, 0) + 1
print(counts)
Counter, from the previous lesson, is this counting loop built in. After from collections import Counter, the call Counter(levels) gives Counter({'warn': 3, 'error': 1, 'info': 1}). A Counter is a dict that counts, and reading a missing key gives 0 instead of an error. It still walks every item, so it costs the same O(n). Write the loop until it comes without thinking, and use Counter when you can say what it does.
A count can also stop the walk early. A rate limiter watches a stream of user ids and flags the first user whose count goes above a limit k. It does not need the final counts: it can stop the moment one count passes k. Build it from its lines.
Put the lines in order to build first_over_limit(user_ids, k). It walks the ids in order and returns the first id whose count goes above k, or None if no count ever does. Indentation is part of each line. Three lines do not belong.
Add lines from the list below, in order.
def first_over_limit(user_ids, k):if counts[user] > k:counts = {}counts = {}return Nonereturn Nonecounts[user] = counts.get(user, 0) + 1return usercounts[user] += 1for user in user_ids:
Recap. Counting keeps a dict from item to count and updates it once per item with counts[x] = counts.get(x, 0) + 1. The promise (every item visited so far has its exact count) makes the final dict the answer, for one O(n) walk.
Anagrams are a counting question
Two strings are anagrams when one is a rearrangement of the other: "stop" and "pots" use the same letters, each the same number of times. How do you check that without trying every rearrangement?
Order does not matter, only the counts do. So count the letters of each string with the loop above, then compare the two dicts. Two dicts are equal (==) when they hold the same keys with the same value for each key. The order in which the keys went in does not count.
One tempting shortcut fails. A set keeps which items appear, not how many times. Predict all three lines:
Type exactly what this prints, one value per line. set("aab") builds a set from the letters of the string.
print({"a": 1, "b": 2} == {"b": 2, "a": 1})
print({"a": 2, "b": 1} == {"a": 1, "b": 2})
print(set("aab") == set("abb"))
Now the full problem. Count each string in its own dict, then compare.
The counts are the whole question. Each string is walked once, so for strings of n letters the time is O(n). Each dict has at most 26 keys, because the strings hold only the letters a to z, so the extra space is O(1): a fixed amount, however long the strings are. Counter(s) == Counter(t) is the same check in one line. Sorting both strings and comparing also works, at O(n log n); counting is the faster answer.
Seen-before: check, then add
The second question: has this value appeared before? You do not need a count for that, only a yes or a no. The notebook is a set: a collection of different values with no positions and no counts. Module 0's duplicate check used one. user in seen answers True or False in about one step on average, and seen.add(user) puts a value in.
A deduplication step in a pipeline does exactly this: it marks each record new or repeat as the records stream past. Before you step through, guess the five lines this prints.
def flag_repeats(user_ids):seen = set()for user in user_ids:if user in seen:print(user, "repeat")else:print(user, "new")seen.add(user)
(nothing printed yet)The order of the two moves is the whole pattern: check first, then add. Before each check, seen holds exactly the ids to the left of the current one. Add first, and every id finds itself: the first "ana" would print repeat.
Which move comes first depends on the question. The rate limiter counted first, because "has this user gone over k?" includes the event in front of it. Seen-before asks only about the items before the current one, so it checks first.
Here is module 0's duplicate check as a full problem. Write it from a blank editor, and stop at the first repeat.
The loop can stop at the first repeat. The one-liner len(set(nums)) < len(nums) gives the same answer (building a set drops repeats, so a shorter set means something repeated) at the same O(n) cost, but it always reads the whole list, even when the repeat sits at positions 0 and 1.
Two sum: seen-before with a partner
Here is the problem: you get a list nums and a number target, and exactly one pair of different positions holds two numbers that add up to target. Return the two positions, smaller first. With [4, 1, 6, 3, 5] and target 8, the answer is [3, 4], because 3 + 5 = 8.
Start with the brute force: check every pair. A brute force is the plain approach that tries every possibility. The outer loop picks a position i, and the inner loop picks every position j to its right. Guess first: how many pairs does it check, counting the pair 3 and 5 that works?
def two_sum(nums, target):checks = 0for i in range(len(nums)):for j in range(i + 1, len(nums)):checks += 1if nums[i] + nums[j] == target:return [i, j]
(nothing printed yet)The count follows a pattern. The first number was tried with the 4 numbers to its right, the second with 3, then 2, then 1: 4 + 3 + 2 + 1 = 10. With n numbers that sum is n(n − 1)/2 pairs: 10 for 5 numbers, and about 50 million for 10,000. That is O(n2) time. It needs no notebook, so its extra space is O(1).
Where is the wasted work? Fix a number x. Only one value can complete its pair: target - x, which we call its partner (solutions online often call it the complement). So for each x the inner loop asks one question, "is my partner in the rest of the list?", and answers it by scanning. Turn the question around: as the walk reaches each number, ask whether its partner is among the numbers already passed. That is the seen-before question, asked about the partner instead of x itself, and a hash map answers it in about one step. No pair is missed: the later of its two numbers finds the earlier one.
The notebook must be a dict, not a set. The problem asks for positions. A set could say the partner exists but not where it was. So the dict seen maps each number passed to its position. Same list, same target. Guess first: how many lookups does it make before it returns?
def two_sum(nums, target):seen = {}for i, x in enumerate(nums):partner = target - xif partner in seen:return [seen[partner], i]seen[x] = i
(nothing printed yet)Why look up before storing? Look at the first pass: the target is 8 and the first number is 4, so the 4 is its own partner. If line 7 ran before line 5, the 4 would be in seen when we looked for its partner, and storing first would pair position 0 with itself. The bug hides on many inputs, which is why it survives a quick test:
This version stores each number before it looks for the partner. Type exactly what the two calls print, one per line.
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
seen[x] = i # stored before the lookup
partner = target - x
if partner in seen:
return [seen[partner], i]
print(two_sum([2, 7, 11, 15], 9))
print(two_sum([4, 1, 6, 3, 5], 8))
Looking up first still lets two equal numbers pair. On [3, 3] with target 6, the first 3 finds seen empty and is stored at position 0. The second 3 looks for 3, finds position 0, and returns [0, 1]. Those are two different positions, so the pair is real. The rule stops a position from pairing with itself, not a value.
Why return [seen[partner], i] in that order? Everything in seen is to the left of i, so the partner's position is always the smaller one. The answer comes out sorted without a sort.
The promise is the proof. Say the answer pair sits at positions a < b. When the walk reaches b, the number at a is already in seen, so the lookup succeeds there, if it has not returned earlier. And it never returns a wrong pair, because it returns only when two numbers at different positions do add up to the target.
Trace it once on paper before you write it. Tracing by hand is the habit that catches bugs in a round with no run button.
On paper, trace the dict version of two sum on two_sum([6, 5, 2, 7, 9], 12). Write one row per position the walk reaches: i, x, partner, whether the partner is in seen, and seen after the row. Reveal the steps one at a time to check your rows.
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.
Now write it from a blank editor.
Recap. The brute force checks every pair: O(n2) time, no notebook. Two sum in one walk asks a seen-before question about the partner, target - x, and keeps a dict of positions because the answer is positions. Look up first, then store, so no position pairs with itself.
Both notebooks at once
What if the question is how many pairs, not which one? Change one thing in two sum, and the notebook changes with it. Count every pair of positions that adds up to the target. On [1, 5, 3, 3, 3] with target 6 there are 4: the 1 with the 5, and three different pairs of 3s. Positions no longer matter, but how many copies of the partner you have passed does: each earlier copy of the partner makes one new pair. When the walk reaches the last 3, at position 4, two 3s sit to its left, at positions 2 and 3, so it adds two pairs. So the notebook is a count, and the walk still checks before it adds.
Write count_pairs(nums, target), which returns how many pairs of positions i < j have nums[i] + nums[j] == target. Equal values at different positions make different pairs: [3, 3, 3] with target 6 has three. Use one walk, with a count as the notebook. Then press Watch it run to see the dict change.
raise NotImplementedError, then press Run tests. Each check says what it expects.This shape (add the partner's count, then count the current number) comes back in the prefix sums lesson at the end of this module, where it counts the stretches of neighboring numbers that add up to a target.
Last, say the plan out loud, the way you would in the room.
Explain, as you would in the plan step before typing, how you will solve two sum. Name the brute force and its cost first. Then give the walk, the notebook, the promise and the cost of the better approach, and say why the notebook is a dict and not a set.
Saved in this browser as you type.