Project: find duplicates fast
Python · Unit 22: Complexity
- Full plan
- Python
- Project
- 3 exercises
To know whether a list has duplicates, the slow way compares each number with all the ones ahead of it: with 4 numbers that is 6 comparisons, with 1000 it is almost half a million.
With a set one pass is enough, because asking whether you have seen it is O(1).
nums = [4, 9, 1, 9]
n = len(nums)
steps = 0
for i in range(n):
for j in range(i + 1, n):
steps += 1
print(steps)Prints
6
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Complete the code
Complete it so the function reports when a number has already shown up before.
2. Write the code
Write
has_repeat(nums): it returnsTrueif some number shows up twice andFalseif not. Use a set to remember the ones you have seen, in a single pass.3. Write the code
Now prove it by counting.
check(nums)returns a list with two things: whether there is a duplicate, and how many numbers it looked at before answering. Add one step per number you look at and leave as soon as you find the duplicate.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.