Algorithms · Hash maps

Contains Duplicate

Does any number appear twice?

The problem

Return True if any number appears more than once in nums, otherwise False.

has_duplicate([4, 1, 9, 1])True
has_duplicate([1, 2, 3, 4])False
Hash maps. Remember what you’ve seen. A coat check: hand over your ticket and get your coat back instantly, however many coats there are.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def has_duplicate(nums):take a list of numbers
for i in range(len(nums)):pick each position i
for j in range(i + 1, len(nums)):compare it with every later position j
if nums[i] == nums[j]:the same number twice?
return Truefound a duplicate
return Falsechecked every pair: no duplicates

Now ask: what if there were a billion?

Chrome checks every address you visit against millions of known dangerous sites. A set that big won’t fit on your phone, so Chrome uses a Bloom filter: a tiny set that’s allowed to be very slightly wrong.

Aim for O(n)🌱 warm-up

Think it through

You’re walking through the list. What would let you spot a repeat the moment it appears?

  • Remembering every number you’ve seen
  • Comparing with the next number
Show the answer

Remembering every number you’ve seen. A repeat can be far away, so neighbours aren’t enough. Remember what you’ve seen, then each new number asks one question: “seen it?”.

Which answers “have I seen x?” fastest?

  • x in a_list
  • x in a_set
Show the answer

x in a_set. A list checks item by item; a set jumps straight to the answer (it’s a hash table). Same line of code, wildly different speed: one of the most useful things to know in Python.

Stuck? 3 nudges, smallest first
  1. As you walk through the list, you need to remember every number you’ve already seen.
  2. Careful: x in a_list secretly checks every item, one by one. x in a_set jumps straight to the answer.
  3. Make seen = set(). For each x: if x in seen, return True; otherwise seen.add(x).

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
def has_duplicate(nums):take a list of numbers
seen = set()numbers we've already met
for x in nums:look at each number once
if x in seen:met it before? (one step, thanks to hashing)
return Truefound a duplicate
seen.add(x)remember it
return Falsenever met anything twice

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with hash maps