First Repeat
Read a list from left to right. Return the first value that you have already seen earlier in the list. If no value ever repeats, return None.
Write first_repeat(items).
Understand the problem
The word "first" can mean two things. Find out which one this task uses.
For [5, 2, 1, 2, 3, 5], which value does first_repeat return?
521
Reading left to right, the first time you meet a value you have already seen is at position 3, where the second 2 appears. The second 5 only comes at position 5, later. So the answer is 2 even though 5 appeared in the list first. The task is about when the repeat happens.
What should first_repeat([1, 2, 3]) return? Type the word.
Nothing repeats, so the answer is None.
Try examples by hand
Think about the work involved.
At position 4 of a list (counting from 0), how many earlier items must you check to know whether the item at position 4 has been seen?
Positions 0, 1, 2 and 3 are earlier: 4 items. In general, position i has i earlier items, so the work grows with the position.
A list has 10,000 distinct values and a repeat only at the very end. Roughly how many comparisons will "look back through the earlier items" make in total?
- About 10,000
- About 50,000,000
- About 100
The checks cost 0 + 1 + 2 + ... + 9,999, which is about 10,000 x 10,000 / 2 = 50 million. The work grows with the square of the length.
Write the brute force
Do not look for the clever answer yet. Write the simplest version that is correct, even if it is slow. A correct slow answer gives you something to test against and something to improve.
def first_repeat(items):
# Write the simple version here. It only has to be correct, not fast.
pass
Hint 1: a question to ask yourself
For each position, what question do you have to answer about the items before it?
Hint 2: the shape of the answer
Loop over the positions. For each item, check whether it appears in the part of the list before that position (a slice such as items[:i]).
Find the bottleneck
Before you improve anything, find what is slow. Answer these, then write the faster version.
What is repeated again and again in your brute force?
- Looking through all earlier items for one value
- Reading the list from the left
- Returning the answer
Every position re-reads the whole earlier part of the list. The same earlier items are scanned over and over.
Which structure answers "have I seen this value?" in about one step, and remembers values you add as you go?
- A list
- A set
- A string
A set keeps each value once and uses hashing, so x in seen takes about the same time however large the set is. A list has to look at its items one by one.
Make it faster
Now write the version that reads the list once.
def first_repeat(items):
# Write the faster version here.
pass
Hint 1: a question to ask yourself
What could you carry along while reading, so that you never have to look back?
Hint 2: the pattern
Keep a set of the values seen so far.
Hint 3: pseudocode
seen = empty set
for each item:
if item is in seen: return item
add item to seen
return None
Reflect
Brute force: O(n squared)
def first_repeat(items):
for i in range(len(items)):
if items[i] in items[:i]:
return items[i]
return None
Improved: O(n)
def first_repeat(items):
seen = set()
for item in items:
if item in seen:
return item
seen.add(item)
return None
Pattern: a set is a memory of what you have seen. Any task that asks "have I met this before?" while scanning is a set (or dictionary) task. The loop touches each item once, and every question about the past is a quick lookup.
Cost:
| Version | Time | Extra space |
|---|---|---|
| Look back through earlier items | O(n squared) | O(1) for the check (the slice copy costs more) |
| Set | O(n) | O(n) |
Stopping early: the set version returns as soon as it finds the first repeat, so on lists that repeat early it reads only the start.
What an interviewer might ask next: What if you had to return all the values that repeat, or count how many times each one repeats? (That is a dictionary of counts, the next problems.)
import random
VISIBLE = 3
CASES = [
(([5, 2, 1, 2, 3, 5],), 2, 'the repeat that happens first, not the value that appeared first'),
(([1, 2, 3],), None, 'no repeat'),
(([4, 4],), 4, 'a repeat right at the start'),
(([],), None, 'empty list'),
(([7],), None, 'one item'),
((['a', 'b', 'c', 'a', 'b'],), 'a', 'words instead of numbers'),
(([9, 8, 7, 6, 5, 4, 9],), 9, 'a repeat only at the end'),
(([0, 1, 0],), 0, 'zero repeats'),
]
def REFERENCE(items):
seen = set()
for item in items:
if item in seen:
return item
seen.add(item)
LIMIT = 2.0
def PERF():
rng = random.Random(7)
items = list(range(30000))
rng.shuffle(items)
items.append(items[10])
other = list(range(100000))
rng.shuffle(other)
return [('30000 values, one repeat at the end', (items,)), ('100000 values, no repeat', (other,))]