5/40
Part 1 of 7 · Sets and seen-setsLearn and do
Remember what you've seen
The first pattern is the one you'll use most, and part 1 of the blank-editor lesson ended on it. Walk the input once, and keep a seen-set: a set of everything you've passed.
One pass with a seen-set replaces comparing every pair
Is there a duplicate in this list?
# compare every pair
def has_duplicate_pairs(items):
for i in range(len(items)):
for j in range(i):
if items[i] == items[j]:
return True
return False
The faster way walks the list once and keeps a set of what it has passed. For each item, ask whether it's already in the set: if it is, that's a duplicate, and if not, add it. Here it is on a short input, one step per item:
Item of ["b", "a", "c", "a"] | seen, before the check | In seen? |
|---|---|---|
| "b" | { } | no: add "b" |
| "a" | {"b"} | no: add "a" |
| "c" | {"b", "a"} | no: add "c" |
| "a" | {"b", "a", "c"} | yes: return True |
The every-pair version compares each item with every item before it. With no duplicate, that's pairs, n times n minus 1, halved: 499,500 for a thousand items.
The seen-set version hashes each item once.
Keep the loop, but make seen a list. What does each item in seen cost now?
Pick an answer above to see the rest