Spotting repeats: the seen set
After this: Write the one pattern behind finding repeats and removing them.
On this page · 6 sections · 4 checks
The last lesson used a set to compare two groups. This lesson uses a set to go through one list and remember what it has already seen.
Does [4, 1, 7, 1, 9] contain a repeat? You can find out by going through it and remembering what you have seen.
- The first item is 4. You have not seen it, so remember it. You have seen 4.
- The next item is 1. You have not seen it, so remember it. You have seen 4 and 1.
- The next item is 7. You have not seen it, so remember it. You have seen 4, 1 and 7.
- The next item is 1. You have seen it already, so the answer is yes.
The loop only ever asks one question: have I seen this before? That is a membership test.
Remembering with a list
The first version you might write keeps the seen items in a list.
def has_repeat(items): seen = [] for item in items: if item in seen: # a list scan: every item seen so far return True seen.append(item) return Falsestatic boolean hasRepeat(int[] items) { List<Integer> seen = new ArrayList<>(); for (int item : items) { if (seen.contains(item)) { // a list scan: every item seen so far return true; } seen.add(item); } return false;}The code is correct, but it can be slow. The test item in seenseen.contains(item) looks through the list, one item at a time. So when there are no repeats, the first item makes 0 comparisons, the second makes 1, the third makes 2, and so on.
For 5 items, that is 0 + 1 + 2 + 3 + 4 = 10 comparisons. For n items, it is about n²/2 comparisons. The symbol n² means n × n, and a cost like this is written O(n²): if you double the data, you make four times as many comparisons. For a million items, that is about half a trillion comparisons.
Remembering with a set
Now make seen a set. The loop stays the same, except that append becomes add. Only the cost changes.The loop stays the same, and only the cost changes. Each question hashes the item, goes to one slot and compares a short chain. A question costs O(1) on average, so the whole loop costs O(n) on average: the work grows at the same rate as the list. For a million items, that is about a million questions.
The same loop can return the repeat itself, not only say yes.
def first_repeat(items): seen = set() for item in items: if item in seen: # seen before? hash, slot, a short chain return item seen.add(item) # remember it return None
print(first_repeat("the cat saw the dog".split()))the
static String firstRepeat(String[] items) { Set<String> seen = new HashSet<>(); for (String item : items) { if (seen.contains(item)) { // seen before? hash, slot, a short chain return item; } seen.add(item); // remember it } return null;}
System.out.println(firstRepeat("the cat saw the dog".split(" ")));the
Here is how to read it.
seenstarts as an empty set.- For each item, the loop asks first: is it in
seen? If so, this item is the first repeat, and the function returns it. - If not, the loop adds the item to
seenand moves on. - If the loop reaches the end, there was no repeat, so the function returns Nonenull.
This pattern is called the : ask first, then add. It is the idea behind "are there any repeats?", "what is the first repeated item?" and "remove the repeats". The lesson Hash maps in practice used it, and graph searches use it too.
Watch it happen
Here are the words the cat saw the dog, one word at a time. For each word, ask first and then add. The table is the seen set.
- Contains? theThis is the first word. Seen it before? Slot 1 is empty, so no.
- Add the
- Contains? cat
- Add cat
- Contains? saw
- Add saw
- Contains? the
- 0—
- 1—
- 2—
- 3—
- 4—
- 5—
- 6—
- 7—
Start with the first task above, or try any key.
- count
- 0
- load
- 0.00
- compares
- 0
Keeping the order
Removing the repeats from a list is called . It uses the same loop, and it keeps each item the first time it appears. Here is [4, 1, 7, 1, 9, 4].
- 4 is new, so keep it. The result is
[4]. - 1 is new, so keep it. The result is
[4, 1]. - 7 is new, so keep it. The result is
[4, 1, 7]. - 1 is in the seen set, so skip it.
- 9 is new, so keep it. The result is
[4, 1, 7, 9]. - 4 is in the seen set, so skip it.
The code has two collections. The seen set answers the question, and the result list keeps the order, because a set does not.
def dedupe(items): seen = set() result = [] for item in items: if item in seen: # a repeat: skip it continue seen.add(item) result.append(item) # first appearance: keep it, in arrival order return result
print(dedupe([4, 1, 7, 1, 9, 4]))[4, 1, 7, 9]
static List<Integer> dedupe(int[] items) { Set<Integer> seen = new HashSet<>(); List<Integer> result = new ArrayList<>(); for (int item : items) { if (seen.contains(item)) { // a repeat: skip it continue; } seen.add(item); result.add(item); // first appearance: keep it, in arrival order } return result;}
System.out.println(dedupe(new int[] {4, 1, 7, 1, 9, 4}));[4, 1, 7, 9]
Check yourself
first_repeatfirstRepeat is the function from this lesson. What does this print?
print(first_repeat(["dog", "cat", "fox", "cat", "dog"]))System.out.println(firstRepeat(new String[] {"dog", "cat", "fox", "cat", "dog"}));What does this print?
seen = set()out = []for ch in "mississippi": if ch not in seen: seen.add(ch) out.append(ch)print(out, len(seen))Set<Character> seen = new HashSet<>();List<Character> out = new ArrayList<>();for (char ch : "mississippi".toCharArray()) { if (!seen.contains(ch)) { seen.add(ch); out.add(ch); }}System.out.println(out + " " + seen.size());Complete first_repeatfirstRepeat. The missing line asks whether the item has been seen before, so that the next line can return it.
def first_repeat(items): seen = set() for item in items: ______________________ # ← seen before? return item seen.add(item) return Nonestatic String firstRepeat(String[] items) { Set<String> seen = new HashSet<>(); for (String item : items) { ______________________ // ← seen before? return item; } seen.add(item); } return null;}seen could be a list, and the code would still give the right answer. So why use a set?
Connect
When you only need each value once, the library can do the loop for you.
items = [4, 1, 7, 1, 9, 4]print(sorted(set(items))) # each value once; a set has no promised order, so sortprint(list(dict.fromkeys(items))) # each value once, in arrival order: a dict remembers the order[1, 4, 7, 9] [4, 1, 7, 9]
List<Integer> items = List.of(4, 1, 7, 1, 9, 4);System.out.println(new TreeSet<>(items)); // each value once, sortedSystem.out.println(new LinkedHashSet<>(items)); // each value once, in arrival order[1, 4, 7, 9] [4, 1, 7, 9]
- Write the seen-set loop: ask first, then add.
- Use it to find the first repeat and to remove repeats, keeping the arrival order when it matters.
- Say why a seen list costs O(n²) and a seen set costs O(n) on average.