Remove Duplicates, Keep Order
Write remove_duplicates(items) that returns a new list with each distinct item once, keeping the first occurrence and the original order. The items are hashable (numbers, strings, tuples).
[3, 1, 3, 2, 1] becomes [3, 1, 2]. The tests include long lists, so a slow first idea will time out.
Understand the problem
Look at what a set can and cannot do.
Can you rely on the order of list(set([3, 1, 3, 2]))?
- Yes, it keeps the first occurrences in order
- No, a set has no promised order
A set is built for fast membership tests, not for order. Its order depends on the hash values and can change. The task needs the order, so a plain set conversion is not enough.
Since Python 3.7 which built-in container remembers insertion order and also ignores repeated keys?
- A
list - A
dict - A
tuple
A dictionary keeps keys in the order they were first added, and a repeated key does not add a second entry. dict.fromkeys(items) makes a dictionary of the distinct items in first-seen order.
1, 1.0 and True are all equal in Python and have the same hash. How many of them stay in remove_duplicates([1, 1.0, True])?
- 3
- 1
- 2
They compare equal, so after the first (1) the others count as duplicates. Only [1] is left. Equal values with different types are an edge case of any "distinct" operation.
Write the brute force
Write the simplest version that is correct, even if it is slow. Then you have something to test against and something to improve.
def remove_duplicates(items):
# Write the simple version here. It only has to be correct, not fast.
pass
Hint 1: a question to ask yourself
For each item, how do you know whether you have already kept it?
Hint 2: the shape of the answer
Build a result list. For each item, if it is not already in the result list, append it.
Find the bottleneck
Where does the time go?
item not in result on a list looks at the items one by one. For 30,000 different items, about how many comparisons does the whole loop make?
- About 30,000
- About 450 million
- About 30 million
The first item is compared with 0, the second with 1, the third with 2 ... the last with about 30,000: roughly 30,000 x 30,000 / 2 = 450 million. A list is the wrong tool for repeated "have I seen this?" questions.
Which container answers "have I seen this?" in about one step?
- A list
- A set or a dict
- A string
Sets and dicts use hashing, so membership is O(1) on average. You need both the speed (a set) and the order (the result list), so keep both.
Make it faster
Make the check fast and keep the order.
def remove_duplicates(items):
# Write the faster version here.
pass
Hint 1: a question to ask yourself
Can you keep the result list for the order and something else for the fast check?
Hint 2: the pattern
A seen set for the check, and a result list for the order. Or one line with dict.fromkeys.
Hint 3: pseudocode
seen = empty set
result = empty list
for item in items:
if item is not in seen:
add item to seen
append item to result
return result
Reflect
Brute force: O(n squared)
def remove_duplicates(items):
result = []
for item in items:
if item not in result:
result.append(item)
return result
Improved: a set for speed, a list for order
def remove_duplicates(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
Another way: one line with dict.fromkeys
def remove_duplicates(items):
return list(dict.fromkeys(items))
What this tests: sets, dictionaries, insertion order, hashing, and spotting a hidden O(n squared) inside a loop (in on a list).
The pattern: to remove duplicates and keep order you need two things: a fast "seen" check (a set) and an ordered output (a list or a dict). dict.fromkeys gives both in one line and is the idiom to know.
Hashable only: both fast versions need hashable items. For a list of lists you would convert each item to a tuple, or fall back to the slow in result check.
Cost:
| Version | Time |
|---|---|
not in result (list) |
O(n squared) |
set or dict.fromkeys |
O(n) |
What an interviewer might ask next: Keep the last occurrence of each item instead. (Reverse, dedupe, reverse again.)
import random
VISIBLE = 3
CASES = [
(([3, 1, 3, 2, 1],), [3, 1, 2], 'a normal list'),
(([],), [], 'an empty list'),
((['a', 'b', 'a'],), ['a', 'b'], 'text items'),
(([3, 3, 3],), [3], 'all the same'),
(([5, 4, 3],), [5, 4, 3], 'no duplicates, not sorted'),
(([1, '1', 1.0],), [1, '1'], 'equal numbers of different types'),
(([(1, 2), (1, 2), (2, 1)],), [(1, 2), (2, 1)], 'tuples'),
(([None, 0, None],), [None, 0], 'None is an item too'),
]
def REFERENCE(items):
return list(dict.fromkeys(items))
LIMIT = 2.0
def PERF():
rng = random.Random(4)
many = list(range(30000))
rng.shuffle(many)
many = many + many[:5000]
return [('35000 items, 30000 different', (many,)), ('200000 items', ([rng.randint(0, 50000) for _ in range(200000)],))]